Check if string begins with something? [duplicate] Check if string begins with something? [duplicate] javascript javascript

Check if string begins with something? [duplicate]


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.