Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to except coma in search word in RegExp javascript

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading