[英]Remove the string on the beginning of an URL
我想从 URL 字符串的开头删除“ www.
”部分
例如在这些测试用例中:
例如www.test.com
→ test.com
例如www.testwww.com
→ testwww.com
例如testwww.com
→ testwww.com
(如果它不存在)
我需要使用 Regexp 还是有智能功能?
取决于你的需要,你有几个选择,你可以这样做:
// 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\.)/,"");
是的,有一个 RegExp,但您不需要使用它或任何“智能”函数:
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 = originalStrint.substr(4)
您可以使用 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
手动,例如
var str = "www.test.com",
rmv = "www.";
str = str.slice( str.indexOf( rmv ) + rmv.length );
或者只是使用.replace()
:
str = str.replace( rmv, '' );
尝试以下
var original = 'www.test.com';
var stripped = original.substring(4);
其他方式:
Regex.Replace(urlString, "www.(.+)", "$1");
const removePrefix = (value, prefix) =>
value.startsWith(prefix) ? value.slice(prefix.length) : value;
您可以剪切 url 并使用 response.sendredirect(new url),这会将您带到与新 url 相同的页面
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.