字符串常见方法

字符串常见方法

  • indexOf( data, start );
      用于返回某个数组或者字符串中规定字符或者字符串的位置;
var str = "hello world";
console.log(str.indexOf("o"));          // 4
console.log(str.indexOf("o",5));        // 7
console.log(str.indexOf("o",8));        // -1
  • chartAt( index )
      返回指定位置的字符,index为下标
var str = "hello world";
console.log(str.charAt(3));             // l
console.log(str.charAt(6));             // w
  • slice(m,n)
      根据指定位置,截取子串,从m到n,不包括n
var str = "hello world";
console.log(str.slice(2,7));            // "llo w"
  • substr(m,n)
      根据指定位置,截取子串,从索引m位置开始取,取n个
var str = "hello world";
console.log(str.substr(2,7));           // "llo wor"
  • substring(m,n):同slice(m,n)一样
      根据指定位置,截取子串,从m到n,不包括n
      如果不指定结束位置,则从开始位置到结尾
var str = "hello world";
console.log(str.substring(2,7));        // "llo w"
  • replace( oldstr, newstr )
      替换,每次只能替换一个符合条件的字符
var str = "hello world";
console.log(str.replace("o","哦"));     // hell哦 world 
console.log(str.replace("o","哦"));     // hell哦 world

"因为.replace()没有修改原字符;想要多次替换,如下:"
var a = str.replace("o","哦");        
console.log(a)                          // hell哦 world
console.log(a.replace("o","哦"))        // hell哦 w哦rld
  • split( ):将字符转成字符
      通过指定字符分割字符串,返回一个数组
var str = "hello world";
console.log(str.split())                // Array [ "hello world" ]
console.log(str.split(""))              // Array(11) [ "h", "e", "l", "l", "o", " ", "w", "o", "r", "l", … ]
console.log(str.split("o"))             // Array(3) [ "hell", " w", "rld" ]
原文地址:https://www.cnblogs.com/wufenfen/p/11772045.html