全网 字符串操作实例 最全!

217 阅读3分钟

字符串操作

concat

返回值:新的拼接好的字符串

var text1 = "Hello";
var text2 = "World";
text3 = text1.concat(" ",text2);

includes

检测是否包含指定字符串

 var str = "hello world";
 var result = str.includes("o");
 console.log(result);//true
 var result1 = str.includes("o", 8);
 console.log(result1);//false

startsWith

startsWith() 方法用于检测字符串是否以指定的子字符串开始。
如果是以指定的子字符串开头返回 true,否则 false。
startsWith() 方法对大小写敏感。

var str = "hello world";
var result = str.startsWith("he");
console.log(result)//true
//当为两个参数时,第二个表示开始位数。
var result = str.startsWith("he",1);
console.log(result)//flase

endsWith

字符串是否以指定字符串结尾

 var str = "hello world";
 //检测尾部
 var result = str.endsWith("world");
 console.log(result);//true
 //检测指定位置是否以指定字符结尾
 var result1 = str.endsWith("wo", 8);
 console.log(result1)//true

repeat

字符串复制指定次数

var str ="6"
var str1 = str.repeat(6);
console.log(str1)//666666

字符串获取索引

indexOf

返回字符串中指定文本首次出现的索引

var str = "The full name of China is the People's Republic of China.";
var pos = str.indexOf("China"); // 17

lastIndexOf

返回指定文本在字符串中最后一次出现的索引

ar str = "The full name of China is the People's Republic of China.";
var pos = str.lastIndexOf("China"); // 51

search

var str = "The full name of China is the People's Republic of China.";
var pos = str.search("locate");

如果未找到指定文本,indexOf()、lastIndexOf()、search() 都返回 -1。

字符串截取

slice

提取字符串的某个部分并在新字符串中返回被提取的部分

var str = "Apple, Banana, Mango";
var res = str.slice(7,13);
//res 的结果是 Banana

substr

此方法类似于 slice(),区别在于第二个参数规定提取部分的长度

var str = "Apple, Banana, Mango";
var res = str.substr(7,6);
//res 的结果是 Banana

substring

定义:返回一个字符串在开始索引到结束索引之间的一个子集(新的字符串,包括开始索引不包括结束索引), 或从开始索引直到字符串的末尾(若省略第二个参数)的一个子集

var str = "Apple, Banana, Mango";
var res = str.substring(7,13);
//res 的结果是 Banana

charAt()

可返回指定位置的字符

var str = "HELLO WORLD";
str.charAt(0); 
// 返回 H

字符串正则方法

match

定义:检索返回一个字符串匹配正则表达式的的结果

a = "12311";
a.match(/1/g);    //["1", "1", "1"],不会返回捕获组
a.match(/8/g);

search

用于检索字符串中指定的子字符串,或检索与正则表达式相匹配的子字符串

var str="Mr. Blue has a blue house";
str.search(/blue/i); // 4

replace

用于在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串

str = "Hello World!";
var n = str.replace("Hello", "你好");

split

指定表示每个拆分应发生的点的字符串。可以是一个字符串或正则表达式

a = "a1b2c3d4";
a.split(/\d{1}/)    //["a", "b", "c", "d", ""]
a.split(/\d{1}/, 3)    //取上面数组的前三位  ["a", "b", "c"]

其他

toUpperCase

将字符串转换为大写

var text1 = "Hello World!";     
var text2 = text1.toUpperCase(); 

toLowerCase

将字符串转换为小写

var text1 = "Hello World!";    
var text2 = text1.toLowerCase();

trim

删除字符串两端的空白符

var str = "       Hello World!        ";
alert(str.trim());