BARNOWL
BARNOWL

Reputation: 3589

check every occurrence of a special character followed by a whitespace using regex

I'm trying to check for every occurrence that a string has an @ at the beginning of a string.

So something like this works for only one string occurance

const comment = "@barnowl is cool"
const regex = /@[a-z]/i;

if (comment.charAt(0).includes("@")) {
  if (regex.test(comment)) {
     // do something 
    console.log('test passeed')
  } else {
      // do something else
  }
} else {
      // do other 
}

but....

What if you have a textarea and a user uses the @ multiple times to reference another user this test will no longer work because charAt(0) is looking for the first character in a string.

What regex test is doable in a situation where you have to check the occurrence of a @ followed by a space. I know i can ditch charAt(0) and use comment.includes("@") but i want to use a regex pattern to check if there is space after wards

So if user does @username followed by a space after words, the regex should pass.

Doing this \s doesn't seem to make the test pass

const regex = /@[a-z]\s/i; // shouldn't this check for white space after a letter ?

demo:

https://jsbin.com/riraluxape/edit?js,console

Upvotes: 0

Views: 203

Answers (3)

gbalduzzi
gbalduzzi

Reputation: 10166

To check for multiple matches instead of only the first one, append g to the regex:

const regex = /@[a-z]*\s/ig;

Your regex with \s actually works, see: https://regex101.com/r/gyMyvB/1

Upvotes: 1

Tsubasa
Tsubasa

Reputation: 1429

Is this what you want? Matching all the occurrences of the mention?

const regex = /@\w+/ig

I used the \w flag here which matches any word character.

Upvotes: 1

joncloud
joncloud

Reputation: 745

I think your expression is very close. There are two things that are missing:

  • The [a-z] match is only looking for one character, so in order to look for multiple characters it needs to be [a-z]+.
  • The flags section is missing the g modifier, which enables the expression to look through the entire text string instead of just the first match.

I believe the regular expression declaration should be adjusted to the following:

const regex = /@[a-z]+\s/ig;

Upvotes: 1

Related Questions