字符串获取:

  • var str= ‘hello’;  str[1]   //e(通过[index]获取对应位置的字符)
  • str.charAt(3)  //o  (通过函数charAt(index)获取对应位置的字符)
  • str.charCodeAt(3) //108  (通过str.charCodeAt(index)获取对应字符的字符编码)

字符串查找:

  • indexOf(substr, start)—返回第一次出现的位置。var str='hello world'; console.log(str.indexOf(‘world’))  //6
  • lastIndexOf(substr, start)—从后向前查找,返回第一个匹配字符串在原字符串中的索引没找到,返回-1.
  • search(str)—-var str='hello world'; console.log(str.search(‘hello’))  //0
  • match(str)—-如果找到,返回一个数组,找不到,返回null。eg. var str='hello world'; console.log(str.match(‘hello’))           //[“hello”, index: 0, input: "hello world"]

字符串替换:

  • replace(srcStr, tarStr)  替换字符串中的子字符串
  • srcStr:将要被替换掉的字符串
  • tarStr:将要用这个字符串将srcStr替换掉
  • 替换成功,返回替换后的结果,否则返回原字符串。
  • var str='abc';  console.log(str.replace(‘a’,’m'))         //mbc

字符串截取:

  • substring(start,end) —end表示子字符串在原串中的结束位置.(子串不包含end) 注意:start>end                        e.g.  var str='hello world'; console.log(str.substring(2,3))  // l
  • substr(start,count)—count表示截取子串的个数。var str='hello world'; console.log(str.substr(2,3)) //  llo
  • slice(start,end)—同substring一样.  start>=end,返回空串

字符串分割:

  • split(separator, limit) 把一个字符串分割成字符串数组。
  • separator:可选,分隔符,即在字符串中查找分割符,并将字符串分割。separator支持正则表达式。
  • limit:可选,该参数可指定返回的数组的最大长度。
  • e.g.  var str="How are you doing today?”;               var n=str.split(" ",3);                                console.log(n);     //  [“How”, "are", "you"]

大小写转换:

  • toLowerCase()  、toUpperCase()  将字符串全部转换为小或大写字母
  • eg. var str = 'ABC'; console.log(str.toLowerCase());
  • toLocalLowerCase()、toLocalUpperCase()  同样作用