检查字符串是否以某事开头?

n00*_*101 260 javascript string match

可能重复:
Javascript StartsWith

我知道我可以这样做^ =看看id是否以某个东西开头,我尝试使用它,但它没有用......基本上,我正在检索网址,我想要设置一个类对于以某种方式开始的路径名元素...

所以,

var pathname = window.location.pathname;  //gives me /sub/1/train/yonks/459087
Run Code Online (Sandbox Code Playgroud)

我想确保对于以/ sub/1开头的每个路径,我可以为元素设置一个类......

if(pathname ^= '/sub/1') {  //this didn't work... 
        ... 
Run Code Online (Sandbox Code Playgroud)

Phi*_*lds 368

使用stringObject.substring

if (pathname.substring(0, 6) == "/sub/1") {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

  • 这可以更通用,如:`var x ="/ sub/1"; if(pathname.substring(0,x.length)=== x){// ...};`.这样你就不再依赖于知道'x'的长度,因为它可能会改变. (21认同)
  • -1:创建一个额外的冗余字符串. (17认同)
  • 这是一个测试用例:http://jsperf.com/starts-with/2.子串方法似乎是我的机器上最快的(使用V8). (9认同)

Ric*_*res 182

String.prototype.startsWith = function(needle)
{
    return this.indexOf(needle) === 0;
};
Run Code Online (Sandbox Code Playgroud)

  • 在'false`的情况下,此函数的性能取决于您要检查的字符串的长度,这对于此用例不是预期的行为 (15认同)
  • -1请参阅此处的注释,以获取不使用此类实施的正当理由:http://stackoverflow.com/a/1978419/560287 (9认同)
  • 这是一个完美的答案(indexOf),而不是被标记为答案的答案. (2认同)

Cro*_*ros 83

您也可以使用string.match()和正则表达式:

if(pathname.match(/^\/sub\/1/)) { // you need to escape the slashes
Run Code Online (Sandbox Code Playgroud)

string.match()如果找到则返回匹配子串的数组,否则返回null.


Rob*_*ohr 38

一个更可重用的功能:

beginsWith = function(needle, haystack){
    return (haystack.substr(0, needle.length) == needle);
}
Run Code Online (Sandbox Code Playgroud)


小智 23

首先,让我们扩展字符串对象.感谢里卡多佩雷斯的原型,我认为使用变量'string'在使其更具可读性的情况下比'needle'效果更好.

String.prototype.beginsWith = function (string) {
    return(this.indexOf(string) === 0);
};
Run Code Online (Sandbox Code Playgroud)

然后就像这样使用它.警告!使代码极具可读性.

var pathname = window.location.pathname;
if (pathname.beginsWith('/sub/1')) {
    // Do stuff here
}
Run Code Online (Sandbox Code Playgroud)

  • 没有添加任何东西. (4认同)