删除 URL 开头的字符串

我想从 URL 字符串的开头删除“ www.”部分

例如,在这些测试案例中:

例如: www.test.comtest.com
例如: www.testwww.comtestwww.com
例如 testwww.comtestwww.com(如果它不存在)

我需要使用 Regexp 还是有一个智能函数?

167935 次浏览

如果字符串的格式始终相同,那么一个简单的 substr()就足够了。

var newString = originalString.substr(4)

试试以下方法

var original = 'www.test.com';
var stripped = original.substring(4);

取决于你需要什么,你有两个选择,你可以做:

// 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\.)/,"");

您可以删除 url 并使用 response. sendredirect (new url) ,这将使您使用新的 url 访问相同的页面

要么手动,比如

var str = "www.test.com",
rmv = "www.";


str = str.slice( str.indexOf( rmv ) + rmv.length );

或者直接使用 .replace():

str = str.replace( rmv, '' );

是的,有一个 RegExp,但你不需要使用它或任何“智能”功能:

var url = "www.testwww.com";
var PREFIX = "www.";
if (url.startsWith(PREFIX)) {
// PREFIX is exactly at the beginning
url = url.slice(PREFIX.length);
}

可以使用 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

另一种方式:

Regex.Replace(urlString, "www.(.+)", "$1");
const removePrefix = (value, prefix) =>
value.startsWith(prefix) ? value.slice(prefix.length) : value;