JS中常用字符串方法


JS中常用字符串方法

1、查找字符串中的字符串 indexOf()  lastIndexOf()

  • indexOf() 方法返回字符串中指定文本首次出现的索引(位置);
  • lastIndexOf() 方法返回指定文本在字符串中最后一次出现的索引;
  • 如果未找到文本, indexOf() 和 lastIndexOf() 均返回 -1;两种方法都接受作为检索起始位置的第二个参数。

2、检索字符串中的字符串 search()

       search() 方法搜索特定值的字符串,并返回匹配的位置;

       indexOf()、search()这两种方法是不相等的。区别在于:

  • search() 方法无法设置第二个开始位置参数。
  • indexOf() 方法无法设置更强大的搜索值(正则表达式)。

3、提取部分字符串

有三种提取部分字符串的方法:

  • slice(startend)
  • substring(startend)
  • substr(startlength)

slice() 方法

  • slice() 提取字符串的某个部分并在新字符串中返回被提取的部分。
  • 该方法设置两个参数:起始索引(开始位置),终止索引(结束位置)。

substring() 方法

  • substring() 类似于 slice()
  • 不同之处在于 substring() 无法接受负的索引。

substr() 方法

  • substr() 类似于 slice()
  • 不同之处在于第二个参数规定被提取部分的长度

4、替换字符串内容 replace()

  • replace() 方法用另一个值替换在字符串中指定的值;
  • replace() 方法不会改变调用它的字符串。它返回的是新字符串;
  • 默认地,replace() 只替换首个匹配。默认地,replace() 对大小写敏感。

5、转换为大写和小写 toUpperCase() toLowerCase()

  • 通过 toUpperCase() 把字符串转换为大写;
  • 通过 toLowerCase() 把字符串转换为小写;

6、concat() 方法

  • concat() 连接两个或多个字符串:

7、String.trim()

  • trim() 方法删除字符串两端的空白符:

8、提取字符串字符

这是两个提取字符串字符的安全方法:

  • charAt(position)
  • charCodeAt(position)

charAt() 方法

  • charAt() 方法返回字符串中指定下标(位置)的字符串:
  • var str = "HELLO WORLD";
    str.charAt(0);            // 返回 H

charCodeAt() 方法

  • charCodeAt() 方法返回字符串中指定索引的字符 unicode 编码:
  • var str = "HELLO WORLD";
    
    str.charCodeAt(0);         // 返回 72