Javascript ----字符串(String)中的方法

涉及字符串时,常用到的几个方法...

----------------------------------------------------------------------------------------------------

1.   charAt() 方法可返回指定位置的字符。

var str="Hello world!";

//charAt()
console.log(str.charAt(0)); //H

2.   concat() 方法用于连接两个或多个字符串。

var str1="Hello ";
var str2="world!";

console.log(str1.concat(str2));

3.  indexOf()  方法返回 某个指定的字符串值 在 字符串中 首次 出现的位置。

注意: 如果没找到,则返回 -1, 对大小敏感

var str="Hello world!";

console.log( str.indexOf("H") );
//0
console.log( str.indexOf("Hello") );
//0
console.log( str.indexOf("world") );
//6
console.log( str.indexOf("h") );
-1

4.  lastIndexOf()  方法返回 返回一个 指定的字符串值 最后 出现的位置, 从后向前查找。

var str="Hello world!";

console.log( str.lastIndexOf("e") );
//0
console.log( str.lastIndexOf("Hello") );
//0
console.log( str.lastIndexOf("world") );
//6
console.log( str.lastIndexOf("h") );
//-1
console.log( str.lastIndexOf("!") );
//11

5. match()  方法  在字符串内检索指定的值,或找到一个或多个正则表达式的匹配。

注意: 此方法返回的是 指定的值(要查找的值),而不是字符串的位置。

var str="Hello world!"
console.log( str.match("world") );
//world
console.log( str.match("World") );
//null
console.log( str.match("world") );
//world
console.log( str.match("worlld") );
//null
console.log( str.match("world!") );
//world!
console.log( str.match("o") );
//o

6. replace()  方法 替换字符, 或替换一个与正则表达式匹配的字符串。

var str="Hello world!"
console.log( str.replace("Hello", "Wonderful") );
//Wonderful world!

7. serach()  方法 查找字符串中的字符 (返回的是 字符在当前字符串中的第一次出现的位置), 或检索与正则表达式相匹配的子字符串。

var str="Hello world!"
console.log( str.search("Hello") );
//0
console.log( str.search("o") );
//4

8.  slice()  方法 截取字符串, 返回值是 截取出来的新字符串。

注意: 规则是 左闭右开(开始位置包括, 结束位置不包括)

var str="Hello happy world!"

console.log( str.slice(1, 3) );
//el
console.log( str.slice(0, 5) );
//Hello
console.log( str.slice(0) );
//Hello happy world!

console.log( str.slice( ) );
//Hello happy world!

9.  split()  方法 分割字符串 / 把字符串分割成字符串数组。

注意:

  1. 如果引号里有空格的话, 那该方法 就以空格为标准,来分割字符串

  2. 如果引号里什么也没有的话,那改方法就会把字符串分割成每个字符

  3. 该方法有两个参数, para2 表示保留分割的位数

  4. 改方法的返回类型是 object类型的

var str="How are you!"

console.log( str.split(" ") );
//["How", "are", "you!"]
console.log( str.split("") );
//["H", "o", "w", " ", "a", "r", "e", " ", "y", "o", "u", "!"]
console.log( str.split() );
//["How are you!"]
console.log( str.split(" ", 3) );

10. substring()  方法 截取字符串(起始位置 与 结束位置之间的)。

注意:

  1. 改方法有两个参数 起始位置, 结束位置 (左闭右开)

  2. 返回类型是String类型的

var str="Hello world!";

console.log(str.substring(1));
//ello world!
console.log(str.substring(1, 5));
//ello
console.log(str.substring());
//Hello world!

11.  toString()  改方法返回字符串( 转成字符串 )。

12. 把字符串转成大、小写  

   toUpperCase(), toLocaleUpperCase() 把字符串转成大写

   toLowerCase(), toLocaleLowerCase() 把字符串转成大写

原文地址:https://www.cnblogs.com/zsongs/p/5125919.html