2

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

Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
Mayank
  • 83
  • 1
  • 9
  • 3
    If you only want to check if a string contains a substring, do `!!~str.indexOf(substr)`, or even better in ES6, `str.contains(substr)`. – Derek 朕會功夫 Aug 25 '16 at 17:41
  • What are you actually trying to do? Can you show us your output that you are looking for – bipen Aug 25 '16 at 17:42
  • @Derek朕會功夫 I guess javascript doen't have any contains method. – Mayank Aug 25 '16 at 17:50
  • 1
    @Mayank If you are not allowed to use `.indexOf` (ie in a homework assignment) you can always check it character by character. – Derek 朕會功夫 Aug 25 '16 at 17:53
  • @bipen In my code.a message containing '(' character is returned from action file to a jsp file and in jsp that message is to be compared with a hardcore message containing '(' in properties file. When compared and true is returned I need to show a error message – Mayank Aug 25 '16 at 17:58

1 Answers1

3

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 )
Community
  • 1
  • 1
Paul
  • 139,544
  • 27
  • 275
  • 264