开发者

Check if string begins with something? [duplicate]

This question already has answers here: How to check if a string "StartsWith" another string? (18 answers) Closed 2 years ago.

I know that I can do like ^= to see if an id starts with something, and I tried using that for this, but it didn't work. Basically, I'm retrieving a URL 开发者_JAVA百科and I want to set a class for an element for path names that start in a certain way.

Example:

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

I want to make sure that for every path that starts with /sub/1, I can set a class for an element:

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


Use stringObject.substring

if (pathname.substring(0, 6) == "/sub/1") {
    // ...
}


String.prototype.startsWith = function(needle)
{
    return this.indexOf(needle) === 0;
};


You can use string.match() and a regular expression for this too:

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

string.match() will return an array of matching substrings if found, otherwise null.


A little more reusable function:

beginsWith = function(needle, haystack){
    return (haystack.substr(0, needle.length) == needle);
}


First, lets extend the string object. Thanks to Ricardo Peres for the prototype, I think using the variable 'string' works better than 'needle' in the context of making it more readable.

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

Then you use it like this. Caution! Makes the code extremely readable.

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


Have a look at JavaScript substring() method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜