Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
117
rated 0 times [  124] [ 7]  / answers: 1 / hits: 13867  / 5 Years ago, mon, august 26, 2019, 12:00:00

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


More From » javascript

 Answers
2

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);




[#6461] Thursday, August 22, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
sonja

Total Points: 541
Total Questions: 113
Total Answers: 114

Location: Anguilla
Member since Sun, Jan 29, 2023
1 Year ago
sonja questions
Mon, Nov 30, 20, 00:00, 4 Years ago
Sun, Oct 11, 20, 00:00, 4 Years ago
Thu, May 21, 20, 00:00, 4 Years ago
Sun, Nov 10, 19, 00:00, 5 Years ago
;