i have string:
const text = 'A Jack# Jack#aNyWord Jack, Jack';
i want search word "Jack" only, but if Jack contain # character, its say true mean match.
i try like:
const text = 'A Jack# Jack#aNyWord Jack, Jack';
const regexpWords = /Jack(?=,|#)/g;
console.log(text.match(regexpWords));
result say: Array ["Jack", "Jack", "Jack"]
My expected output is: Array ["Jack#", "Jack#aNyWord", "Jack", "Jack"]
except word "Jack,"
how can i do with this
>Solution :
If you want the # in the match, then you don’t want a lookahead ((?=___)) because lookahead and lookbehind aren’t included in matches. You haven’t said what should be valid following the #, but if I assume any letter or number, then:
const text = "A Jack# Jack#aNyWord Jack, Jack";
const regexpWords = /Jack(?:#[a-zA-Z0-9]*)?/g;
console.log(text.match(regexpWords));
That says
- Match
Jack - Optionally match
#followed by any number of[a-zA-Z0-9]. I do that by wrapping#[a-zA-Z0-9]*in a non-capturing group ((?:___)) and then making the group optional with?
I’ve used [a-zA-Z0-9]* for the letters following the # because the expression doesn’t have the i flag (case-insensitive matching, would match jack). You could use [a-z0-9]* if you’re going to add the i flag. (You might also use \w, but it allows _ which you may or may not want.)
MDN’s regular expressions documentation is quite good: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions