285

我知道我可以^=查看一个 id 是否以某些东西开头,我尝试使用它,但它没有用。基本上,我正在检索一个 URL,并且我想为以某种方式开始的路径名称的元素设置一个类。

例子:

var pathname = window.location.pathname;  //gives me /sub/1/train/yonks/459087

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

if (pathname ^= '/sub/1') {  //this didn't work... 
        ... 
4

6 回答 6

389

使用stringObject.substring

if (pathname.substring(0, 6) == "/sub/1") {
    // ...
}
于 2009-11-19T23:15:03.193 回答
189
String.prototype.startsWith = function(needle)
{
    return this.indexOf(needle) === 0;
};
于 2012-02-24T11:55:40.450 回答
86

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

if(pathname.match(/^\/sub\/1/)) { // you need to escape the slashes

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

于 2011-09-09T11:22:43.467 回答
41

更多可重用的功能:

beginsWith = function(needle, haystack){
    return (haystack.substr(0, needle.length) == needle);
}
于 2012-01-13T15:54:56.293 回答
26

首先,让我们扩展字符串对象。感谢 Ricardo Peres 的原型,我认为使用变量 'string' 比使用 'needle' 在提高可读性方面效果更好。

String.prototype.beginsWith = function (string) {
    return(this.indexOf(string) === 0);
};

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

var pathname = window.location.pathname;
if (pathname.beginsWith('/sub/1')) {
    // Do stuff here
}
于 2012-05-18T03:30:25.077 回答
2

看看 JavaScriptsubstring()方法。

于 2009-11-19T23:14:16.750 回答