MartinWebb
MartinWebb

Reputation: 2008

JavaScript Regex splitting string into words

I have the following Regex

console.log("Test #words 100-200-300".toLowerCase().match(/(?:\B#)?\w+/g))

From the above you can see it is splitting "100-200-300". I want it to ignore "-" and keep the word in full as below:

--> ["test", "#words", "100-200-300"]

I need the Regex to keep the same rules, with the addition of not splitting words connected with "-"

Upvotes: 3

Views: 180

Answers (1)

The fourth bird
The fourth bird

Reputation: 163217

For your current example, you could match an optional #, 1+ word chars and repeat 0+ times a part that matches a # and 1+ word chars again.

#?\w+(?:-\w+)*
  • #? Optional #
  • \w+ 1+ word characters
  • (?:-\w+)* Repeat as a group 0+ times matching - and 1+ word chars

Regex demo

console.log("Test #words 100-200-300".toLowerCase().match(/#?\w+(?:-\w+)*/g));

About the \B anchor (following text taken from the link)

\B is the negated version of \b. \B matches at every position where \b does not. Effectively, \B matches at any position between two word characters as well as at any position between two non-word characters.

If you do want to use that anchor, see for example some difference in matches with \B and without \B

Upvotes: 4

Related Questions