我想从URL字符串的开头删除"www.
"部分。
例如,在这些测试用例中:
例如:www.test.com
→ test.com
例如:www.testwww.com
→ testwww.com
例如:testwww.com
→ testwww.com
(如果不存在)
我需要使用正则表达式还是有智能函数可用?
我想从URL字符串的开头删除"www.
"部分。
例如,在这些测试用例中:
例如:www.test.com
→ test.com
例如:www.testwww.com
→ testwww.com
例如:testwww.com
→ testwww.com
(如果不存在)
我需要使用正则表达式还是有智能函数可用?
根据你的需求,你有几个选择,可以进行以下操作:
// 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\.)/,"");
indexOf
/slice
检查要优雅得多。 - berezovskyislice()
是 稍微 快一些,但在99.9% 的情况下,这是无关紧要的、过早优化。编写 replace(/^www\./,"")
的代码清晰自明。 - Tom Lord是的,有一个正则表达式,但您不需要使用它或任何“智能”函数:
var url = "www.testwww.com";
var PREFIX = "www.";
if (url.startsWith(PREFIX)) {
// PREFIX is exactly at the beginning
url = url.slice(PREFIX.length);
}
如果字符串的格式始终相同,那么简单的substr()
函数就足够了。
var newString = originalString.substr(4)
testwww.com
→ twww.com
= 失败 - Christophtestwww.com
вҶ’ www.com
= еӨұиҙҘвҖқгҖӮжҲ‘дјҡе°ҪеҠӣж¶ҰиүІе№¶дҪҝе…¶жӣҙеҠ йҖҡдҝ—жҳ“жҮӮпјҢдҪҶдёҚдҝ®ж”№еҺҹж„ҸгҖӮ - talnicolas可以手动完成,例如
var str = "www.test.com",
rmv = "www.";
str = str.slice( str.indexOf( rmv ) + rmv.length );
.replace()
函数:str = str.replace( rmv, '' );
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
String
类上的removePrefix
)发生名称冲突,相反,只需调用.removePrefix
非常方便。由你决定。 - Flavien Volkenconst removePrefix = (value, prefix) =>
value.startsWith(prefix) ? value.slice(prefix.length) : value;
var original = 'www.test.com';
var stripped = original.substring(4);
另一种方式:
Regex.Replace(urlString, "www.(.+)", "$1");