Mayank
Mayank

Reputation: 83

match substring with a string

I am facing a problem in matching a substring with a String. My substring and string are something like

var str="My name is foo.I have bag(s)"
 var substr="I have bag(s)"

now when I use str.match(substr) it returns null probably because match() function takes input as a regex and in my case it gets confused with the '('. I tried using '\'before round brackets but it didn't worked. indexOf() function is working but I am not allowed to use that. I also used test() and exec() but without any success

Upvotes: 2

Views: 1228

Answers (1)

Paul
Paul

Reputation: 141829

In modern engines you can just use String.prototype.includes:

str.includes( substr )

If you want something that works in older browsers and avoids String.prototype.indexOf, you could implement includes, by manually loop through the string:

String.prototype.includes = function ( substr, start ) {
    var i = typeof start === 'number' ? start : 0;
    // Condition exists early if there are not enough characters
    // left in substr for j to ever reach substr.length
    for ( var j = 0; i + substr.length < this.length + j + 1; ++i ) {
        j = substr[j] === this[i] ? j + 1 : 0;
        if ( j === substr.length )
            return true;
    }
    return false;
};

If you are insistent on using a regex test you can use the escape function from this answer, to properly espace the substr to be used in a regex; in this case it adds a backslash before the ( and ):

new RegExp( substr.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') ).test( str )

Upvotes: 3

Related Questions