FreddCha
FreddCha

Reputation: 595

JS - String includes a substring that matches regex

Check if a JavaScript string includes a substring that matches a regex.

I have tried string.includes(substring)

var myString =  "This is my test string: AA.12.B.12 with some other chars";
myString.includes(/^[A-Z]{2}\.\d{2}\.\[A-Z]{1}\.\d{2,3}$/);

True, False

However, code doesn't compile

Upvotes: 12

Views: 20584

Answers (2)

Chris Rocco
Chris Rocco

Reputation: 134

If we look at the docs for String.prototype.includes() we can see it takes a string, not a regular expression. Instead, try RegExp.prototype.test().

Also, since you only want to match a sub-string, you'll need to remove the start and end anchors ^ and $. (More on regex anchors)

Your code becomes:

var myString =  "This is my test string: AA.12.B.12 with some other chars";
var myRegex = /[A-Z]{2}\.\d{2}\.\[A-Z]{1}\.\d{2,3}/;
console.log(myRegex.test(myString));

Upvotes: 5

Nick Parsons
Nick Parsons

Reputation: 50674

You can use .test() on your regular expression to check whether the pattern matches part of the string. As the pattern will need to match only a portion of the string, you will need to remove the ^ and $ characters as your matched pattern can be contained within a line. Also, there is no need to escape the character class bracket as you have tried to do so in your expression (\[), as you want the [ to be treated as a character class, not a literal square bracket:

const myString =  "This is my test string: AA.12.B.12 with some other chars";
const res = /[A-Z]{2}\.\d{2}\.[A-Z]{1}\.\d{2,3}/.test(myString);
console.log(res);

Upvotes: 19

Related Questions