删除URL开头的字符串


105

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

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

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

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


这是一个非常老的问题,但值得指出的是,在2019年,您应该为此使用URL解析器,而不要使用正则表达式
mikemaccana

1
www.com所有这些回复都会使的所有者感到非常难过。
BrainCore

Answers:


234

根据您的需求,您有两种选择,您可以执行以下操作:

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

24
可能最后一个是最佳解决方案。
Christoph'Mar

11
这不是最佳解决方案。创建用于删除子字符串的正则表达式是一个过大的杀伤力!
berezovskyi

4
@berezovskiy,这取决于您的工作,例如,如果您正在制作性能是关键的游戏,那么您是对的,在大多数情况下,IMO最好明确得多并且不要引入性能低下的错误。击中。但是,答案提供了3个不同的示例可供选择。
nicosantangelo '16

7
我非常喜欢最后一种选择。虽然这是事实,使用slice()快,这是情景99.9%不相关的,过早的优化。编写replace(/^www\./,"") 清晰的自记录代码。
汤姆·罗德

5
第一个和第二个解决方案将使第三个示例失败。tutut
Yarek T

13

是的,有一个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);
}

11

如果字符串始终具有相同的格式,则只需一个简单的字符串即可substr()

var newString = originalStrint.substr(4)

4
testwww.comtwww.com=失败
Christoph

1
@Christoph Ya,顺便说一下,他在回答后编辑问题的方式,这就是为什么我提到字符串始终具有相同的格式的原因
talnicolas 2012年

14
@Christoph,它将是“ testwww.comwww.com= FAIL”
talnicolas 2012年

6

无论是手动还是

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

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

或只是使用.replace()

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

1
我喜欢手动方法,因为字符串可以来自变量,而不会弄乱正则表达式。
nha 2015年

5

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

我认为修改String的原型是不好的做法
dman

是的,就像重载任何原型一样,风险是要与另一个方法(在类中removePrefix位于此处String)发生名称冲突,相反,只需调用即可.removePrefix。由你决定。
Flavien Volken

2

尝试以下

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

0

您可以剪切网址并使用response.sendredirect(new url),这将带您进入新网址的同一页面


By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.