skip to Main Content

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

2

Answers


  1. 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

    Login or Signup to reply.
  2. If you want the words with Jack and there must be at least Jack# you can match the part of the string containing Jack# using a negated character class [^,n]* excluding matching comma’s or newlines.

    If there is a match, then split the match on one or more whitspace characters and filter the result containing the word Jack using word boundaries b

    const text = 'A Jack# Jack#aNyWord Jack, Jack';
    const regexpWords = /[^,n]*bJack#[^,n]*/g;
    const m = text.match(regexpWords);
    
    if (m) {
      const result = m[0]
        .split(/s+/)
        .filter(s => s.match(/bJackb/));
    
      console.log(result);
    }

    After the question was edited, you can match all words with Jack:

    bJack[^,s]* or (?<!S)Jack[^,s]*

    See a regex demo for the matches.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search