Answers:
根据您的需求,您有两种选择,您可以执行以下操作:
// this will replace the first occurrence of "www." and return "testwww.com"
"www.testwww.com".replace("www.", "");
// this will slice the first four characters and return "testwww.com"
"www.testwww.com".slice(4);
// this will replace the www. only if it is at the beginning
"www.testwww.com".replace(/^(www\.)/,"");
slice()
是稍快,这是情景99.9%不相关的,过早的优化。编写replace(/^www\./,"")
清晰的自记录代码。
如果字符串始终具有相同的格式,则只需一个简单的字符串即可substr()
。
var newString = originalStrint.substr(4)
testwww.com
→ twww.com
=失败
testwww.com
→ www.com
= FAIL”
您可以使用removePrefix函数重载String原型:
String.prototype.removePrefix = function (prefix) {
const hasPrefix = this.indexOf(prefix) === 0;
return hasPrefix ? this.substr(prefix.length) : this.toString();
};
用法:
const domain = "www.test.com".removePrefix("www."); // test.com
removePrefix
位于此处String
)发生名称冲突,相反,只需调用即可.removePrefix
。由你决定。