JavaScript 字符串对象

JavaScript对象

1 indexOf()  查找某个字符在字符串中第一次出现的位置,如果没有该字符,则返回-1

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <meta name="viewport" content="width=device-width, initial-scale=1.0">
 6     <title>Document</title>
 7 </head>
 8 <body>
 9     <script>
10         var s1 = "abcdefg";
11         //indexOf()  用于查找某个字符在字符串中的索引号,索引号从 0 开始
12          console.log(s1.indexOf("a"));
13          //如果该字符串中并不存在该字符,那么返回一个 -1
14          console.log(s1.indexOf("z"));
15     </script>
16 </body>
17 </html>

 

 

2.根据索引号返回字符串  charAt(index)

可以用来遍历字符串

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        var s1 = "zhang";
        //charAt(index)  根据索引号返回相应的字符
       for(var i=0;i<s1.length;i++){
           console.log(s1.charAt(i));
           
       }
    </script>
</body>
</html>

 

 

3.截取字符串   substr(截取的起始位置,截取几个字符);

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 
 4 <head>
 5     <meta charset="UTF-8">
 6     <meta name="viewport" content="width=device-width, initial-scale=1.0">
 7     <title>Document</title>
 8 </head>
 9 
10 <body>
11     <script>
12         var s1 = "zhangshan";
13         //截取字符串   substr(截取的起始位置,截取几个字符);
14         console.log(s1.substr(2, 3));
15     </script>
16 </body>
17 
18 </html>

 

 

 

4,替换字符

replace(要被替换的字符,替换为的字符); //只会替换第一字符

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 
 4 <head>
 5     <meta charset="UTF-8">
 6     <meta name="viewport" content="width=device-width, initial-scale=1.0">
 7     <title>Document</title>
 8 </head>
 9 
10 <body>
11     <script>
12         //replac(被替换的字符,替换为的字符), 但是只能替换第一个字符
13          var s1 = "zhangshan";
14         s1 = s1.replace("a","b");
15         console.log(s1);
16 
17         //replace()也可以替换字符串
18         var s2 = "abcefg"
19         s2 = s2.replace("abc","ujk");
20         console.log(s2);
21         
22     </script>
23 </body>
24 
25 </html>

 

 

5. 将字符串转换成数组

split("分隔符")

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 
 4 <head>
 5     <meta charset="UTF-8">
 6     <meta name="viewport" content="width=device-width, initial-scale=1.0">
 7     <title>Document</title>
 8 </head>
 9 
10 <body>
11     <script>
12         
13          var s1 = "zhang,shan";
14          s1 = s1.split(",");
15          console.log(s1);
16     </script>
17 </body>
18 
19 </html>

 

posted @ 2020-04-25 22:15  瑾言**  阅读(254)  评论(0编辑  收藏  举报