indexOf
要查找具有另一个字符串的字符串,请使用indexOf
函数:
var i = "this is a test".indexOf("is");
console.log(i);
上面的代码生成以下结果。
![indexOf函数结果](https://www.w3cschool.cn/attachments/jimg/node_js_tutorial/INDEXOF__B241A13069718E460AB1.png)
substr和splice
要从字符串中提取子字符串,请使用substr
或slice
函数。
substr
获取要提取的字符串的起始索引和长度。slice
取起始索引和结束索引:
var s = "this is a test string.".substr(19, 3);
var s1 = "this is a test string.".slice(19, 22);
console.log(s);
console.log(s1);
上面的代码生成以下结果。
![substr和splice结果](https://www.w3cschool.cn/attachments/jimg/node_js_tutorial/SUBSTR_AND_SPLICE__2203791906B1BA17E99F.png)
Split
要将字符串拆分为子字符串,请使用split函数并获取数组作为结果:
var s = "a|b|c|d|e|f|g|h".split("|");
console.log(s);
上面的代码生成以下结果。
![split函数结果](https://www.w3cschool.cn/attachments/jimg/node_js_tutorial/SPLIT__07796568995FFDBD2133.png)
Javascript V8 函数中的trim函数从字符串的开头和结尾删除空格:
var s = " cat ". trim(); console.log(s);