删除URL开头的字符串

时间:2012-03-29 15:34:35

标签: javascript string

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

例如在这些测试案例中:

e.g。 www.test.comtest.com
例如www.testwww.comtestwww.com
例如testwww.comtestwww.com(如果不存在)

我是否需要使用Regexp或是否有智能功能?

8 个答案:

答案 0 :(得分:171)

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

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

答案 1 :(得分:11)

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

var newString = originalStrint.substr(4)

答案 2 :(得分:10)

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

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

答案 3 :(得分:6)

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

答案 4 :(得分:5)

手动,如

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

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

或只使用.replace()

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

答案 5 :(得分:2)

尝试以下

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

答案 6 :(得分:0)

您可以剪切网址并使用response.sendredirect(新网址),这会将您带到与新网址相同的网页

答案 7 :(得分:0)

另一种方式:

Regex.Replace(urlString, "www.(.+)", "$1");