Lup*_*upo 99 javascript string
我想www.
从URL字符串的开头删除" "部分
例如,在这些测试用例中:
例如www.test.com
→ test.com
例如www.testwww.com
→ testwww.com
例如testwww.com
→ testwww.com
(如果不存在)
我需要使用Regexp还是有智能功能?
nic*_*elo 193
取决于你需要什么,你有几个选择,你可以做:
// 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\.)/,"");
Run Code Online (Sandbox Code Playgroud)
tal*_*las 11
如果字符串总是具有相同的格式,那么简单substr()
就足够了.
var newString = originalStrint.substr(4)
Run Code Online (Sandbox Code Playgroud)
ber*_*kyi 10
是的,有一个RegExp,但您不需要使用它或任何"智能"功能:
var url = "www.testwww.com";
var PREFIX = "www.";
if (url.indexOf(PREFIX) == 0) {
// PREFIX is exactly at the beginning
url = url.slice(PREFIX.length);
}
Run Code Online (Sandbox Code Playgroud)
要么手动,就像
var str = "www.test.com",
rmv = "www.";
str = str.slice( str.indexOf( rmv ) + rmv.length );
Run Code Online (Sandbox Code Playgroud)
或只是使用.replace()
:
str = str.replace( rmv, '' );
Run Code Online (Sandbox Code Playgroud)
您可以使用removePrefix函数重载String原型:
String.prototype.removePrefix = function (prefix) {
const hasPrefix = this.indexOf(prefix) === 0;
return hasPrefix ? this.substr(prefix.length) : this.toString();
};
Run Code Online (Sandbox Code Playgroud)
用法:
const domain = "www.test.com".removePrefix("www."); // test.com
Run Code Online (Sandbox Code Playgroud)
const removePrefix = (value, prefix) =>
value.startsWith(prefix) ? value.slice(prefix.length) : value;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
82520 次 |
最近记录: |