JavaScript 字符串
JavaScript 字符串是不可变的(immutable),String 类所定义的方法都不能修改字符串的内容。如果涉及修改,都是返回全新的字符串。
replace()
字符串替换,它没有在原字符串上替换,而是返回了替换后的值:
s = "hello berlin";
s = s.replace("berlin", "james");
注意:
s.replace("a", "b");
只会替换第一次出现的 a,要所有的 a 都替换为 b,应该用如下正则表达式:
s.replace(/a/g, "b");
indexOf()
进行字符串搜索,如果没有找到子串则返回-1.
String.prototype.include = function(s) {
return this.indexOf(s) != -1;
};
var s = "Welcome to my world!";
if(s.include("world")) {
console.log("it works!");
}
search()
进行正则表达式搜索,如果没有找到子串则返回 -1.
if(s.search("world")) {
console.log("find it");
}
if(s.search("/Welcome/")) {
console.log("find it");
}
if(s.search("/welcome.*world/i")) {
console.log("find it");
}
JavaScript 中没有 startsWith()
和 endsWith()
这样的实用函数,可以自己添加:
if (typeof String.prototype.startsWith != 'function') {
String.prototype.startsWith = function(prefix) {
return this.slice(0, prefix.length) === prefix;
};
}
if (typeof String.prototype.endsWith != 'function') {
String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
}
注意 startsWith()
的实现没有使用 indexOf()
,因为 indexOf()
会扫描整个字符串。
trim()
删除字符串前后空格。
split()
将字符串转为数组,可以用正则表达式,如:
var s = " 623205 EA911785091CN AU Alice Hertson ";
console.log(s.trim().split(/\s+/));