JavaScript string方法

发布时间:2022-06-20 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了JavaScript string方法脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

avaScript 字符串(String) 对象


String 对象用于处理已有的字符块。


JavaScript 字符串

一个字符串用于存储一系列字符就像 "John Doe".

一个字符串可以使用单引号或双引号:

实例

VAR carname="Volvo XC60";var carname='Volvo XC60';

你使用位置(索引)可以访问字符串中任何的字符:

实例

var character=carname[7];

字符串的索引从零开始, 所以字符串第一字符为 [0],第二个字符为 [1], 等等

你可以在字符串中使用引号,如下实例:

实例

var answer="IT's alright";var answer="He is called 'Johnny'";var answer='He is called "Johnny"';

或者你可以在字符串中使用转义字符()使用引号:

实例

var answer='It's alright';var answer="He is called "Johnny"";

 


字符串(String)

字符串(String)使用长度属性length来计算字符串的长度:

实例

var txt="Hello World!";document.write(txt.length);var txt="abcDEFGHIJKLMNOPQRSTUVWXYZ";document.write(txt.length);

在字符串中查找字符串

字符串使用 indexOf() 来定位字符串中某一个指定的字符首次出现的位置:

实例

var str="Hello world, welcome to the universe.";var n=str.indexOf("welcome");

如果没找到对应的字符函数返回-1

lastIndexOf() 方法在字符串末尾开始查找字符串出现的位置。


内容匹配

match()函数用来查找字符串中特定的字符,并且如果找到的话,则返回这个字符。

实例

var str="Hello world!";document.write(str.match("world") + "<br>");document.write(str.match("World") + "<br>");document.write(str.match("world!"));

 


替换内容

replace() 方法在字符串中用某些字符替换另一些字符。

实例

str="Please visit Microsoft!"var n=str.replace("Microsoft","Runoob");

 


字符串大小写转换

字符串大小写转换使用函数 toUpPErCase() / toLowerCase():

实例

var txt="Hello World!";       // Stringvar txt1=txt.toUpperCase();   // txt1 文本会转换为大写var txt2=txt.toLowerCase();   // txt2 文本会转换为小写

 


字符串转为数组

字符串使用split()函数转为数组:

实例

txt="a,b,c,d,e"   // Stringtxt.split(",");   // 使用逗号分隔txt.split(" ");   // 使用空格分隔
<!DOCTYPE htML>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="con">
    <h3 id="title" onclick="change()">标题</h3>
</div>
    <script>

        //js内置String对象

        var str = "abcdef";
        //字符串长度是length属性
        alert(str.length);//输出结果 6
        //charAt 传递索引,返回字符
        alert(str.charAt(3));//输出结果 d
        //传递字符串,返回第一次出现的索引,找不到返回-1
        alert(str.indexOf("c"));//输出结果 2
        //substring 截取字符串包含开始索引,不包含结束索引
        alert(str.substring(1,4));//输出结果 bcd
        //substr 截取字符串,包含开始索引,后面的参数是要几个
        alert(str.substr(1,4));//输出结果 bcde
        
        
    </script>
</body>
</html>

 

txt.split("|");   // 使用竖线分隔 
 
 

脚本宝典总结

以上是脚本宝典为你收集整理的JavaScript string方法全部内容,希望文章能够帮你解决JavaScript string方法所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。