skip to Main Content

If I want to do a "whole word" search for a string with special characters, like say "A+", how can I write a Javascript regex that will match the whole word for cases like the following:

  1. Is the only text in the string: "A+"
  1. Is at the end of the string: "You got an A+"

  2. Is at the beginning of the string: "A+ good job!"

  3. Is in the middle: "You did A+ work here."

It should return false for:

  1. Not whole word: "A++"

  2. Not whole word": "You got an A++!"

  3. Other special characters that make it not a whole word: "A+,", "A+-", "A+0", "A+=", "A+"", "A+*", "A+/", etc.

… and many other cases

I’d love to just use b:

 /b(A+)b/g 

…but that seems to interact poorly with special characters (in fact I’m not sure that regex can even match anything…).

2

Answers


  1. You can use lookarounds for this:

    (?<=^|s)A+(?=s|$)
    

    Here we search for A+ surrounded by whitespace symbols or line boundaries.

    const examples = ['A+', 'You got an A+', 'A+ good job!"', 'You did A+ work here.', 'A++', 'You got an A++!', 'A+, A+-, A+0, A+=, A+", A+*, A+/'];
    for (let i = 0; i < examples.length; i++) {
         console.log(examples[i], /(?<=^|s)A+(?=s|$)/.test(examples[i])) 
    }
    

    Outputs:

    A+ true debugger eval code:1:51
    You got an A+ true debugger eval code:1:51
    A+ good job!" true debugger eval code:1:51
    You did A+ work here. true debugger eval code:1:51
    A++ false debugger eval code:1:51
    You got an A++! false debugger eval code:1:51
    A+, A+-, A+0, A+=, A+", A+*, A+/ false
    

    Demo here

    EDIT: How correctly noticed @trincot you can use negative lookarounds with non-whitespace meta sequence to avoid alterations:

    (?<!S)A+(?!S)
    
    Login or Signup to reply.
  2. If you have an environment where a lookbehind assertion is not supported, you can use a capture group.

    (?:^|s)(A+)(?!S)
    

    Explanation

    • (?:^|s) Assert the start of the string or match a whitespace character
    • (A+) Match A and +
    • (?!S) Assert a whitespace boundary to the right

    Regex demo

    const regex = /(?:^|s)(A+)(?!S)/g;
    const s = `A+
    You got an A+
    A+ good job!
    Is in the middle: "You did A+ work here."
    A++
    You got an A++!
    A+,
    A+-
    A+0
    A+=
    A+"
    A+*
    A+/`;
    console.log(Array.from(s.matchAll(regex), m => m[1]))
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search