删除URL开头的字符串

Lup*_*upo 99 javascript string

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

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

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

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

nic*_*elo 193

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

// 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\.)/,"");
Run Code Online (Sandbox Code Playgroud)

  • 可能最后一个是最佳解决方案. (18认同)
  • 这不是最佳解决方案.创建用于删除子字符串的正则表达式是一种过度杀伤! (6认同)
  • @berezovskiy,这取决于您的工作,例如,如果您正在制作性能是关键的游戏,那么您是对的,在大多数情况下,IMO最好是明确得多的,并且不要引入性能低下的错误。击中。但是,答案提供了3个不同的示例可供选择。 (3认同)
  • 我非常喜欢最后一个选项.虽然使用`slice()`确实*稍微快*,但99.9%的情况是不相关的,过早的优化.编写`replace(/ ^ www\./,"")`是清晰的,自我记录的代码. (3认同)
  • @NicoSantangelo,我必须恭敬地不同意。只有最后一个答案的行为符合预期。我的`indexOf`/`slice`检查更加优雅和简洁,但前提是您不介意使用“锤子”并且可以内联正则表达式(如果您需要多次运行它,这很糟糕)每次都会编译,或者如果您需要以某种方式重用前缀)。 (2认同)
  • 第一个和第二个解决方案将使第三个示例失败。t (2认同)

tal*_*las 11

如果字符串总是具有相同的格式,那么简单substr()就足够了.

var newString = originalStrint.substr(4)
Run Code Online (Sandbox Code Playgroud)

  • @Christoph,它将是"`testwww.com`→`www.com` = FAIL" (12认同)
  • `testwww.com`→`twww.com` =失败 (4认同)
  • @Christoph Ya,顺便说一句,他在我回答后编辑了他的问题,这就是为什么我提到**如果字符串始终具有相同的格式**。 (2认同)

ber*_*kyi 10

是的,有一个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);
}
Run Code Online (Sandbox Code Playgroud)

  • 应该使用 [`startsWith()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith) 而不是 `indexOf()`。 (2认同)

jAn*_*ndy 5

要么手动,就像

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

str = str.slice( str.indexOf( rmv ) + rmv.length );
Run Code Online (Sandbox Code Playgroud)

或只是使用.replace()

str = str.replace( rmv, '' );
Run Code Online (Sandbox Code Playgroud)

  • 我喜欢手动方法,因为字符串可以来自变量,而不会有弄乱正则表达式的风险。 (2认同)

Fla*_*ken 5

您可以使用removePrefix函数重载String原型:

String.prototype.removePrefix = function (prefix) {
    const hasPrefix = this.indexOf(prefix) === 0;
    return hasPrefix ? this.substr(prefix.length) : this.toString();
};
Run Code Online (Sandbox Code Playgroud)

用法:

const domain = "www.test.com".removePrefix("www."); // test.com
Run Code Online (Sandbox Code Playgroud)


Arc*_*ald 5

const removePrefix = (value, prefix) =>
   value.startsWith(prefix) ? value.slice(prefix.length) : value;
Run Code Online (Sandbox Code Playgroud)