Aerodynamika
Aerodynamika

Reputation: 8413

How to replace all the words that contain an underscore in a string using Regex and JavaScript?

I want to detect all the words (but not only in English!) with an underscore using regex, and to then place a hashtag in front of them, so, for example the sentence like:

mind_viral immunity is an important element of general_wellbeing

would produce two matches: mind_viral and 'general_wellbeing` and then change the string to

#mind_viral immunity is an important element of #general_wellbeing 

I'm trying to use this regex:

([a-zA-Z]+(?:_[a-zA-Z]+)*)

But it matches all the words, not only those with an underscore.

What could I do differently?

Upvotes: 1

Views: 386

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626845

With the ECMAScript 2018+ compliant JS environments, you may use

s = s.replace(/\p{L}+(?:_\p{L}+)+/gu, '#$&')

Mind the u flag that enables Unicode property classes in JS regexps.

Here,

  • \p{L}+ - matches any one or more Unicode letters
  • (?:_\p{L}+)+ - one or more repetitions of
    • _ - an underscore
    • \p{L}+ - any one or more Unicode letters

Replace with #$&: # is a literal char, and $& is a backreference to the whole match value.

See the JS demo:

const s = "mind_viral immunity is an important element of general_wellbeing виктор_стрибижев привет";
console.log(s.replace(/\p{L}+(?:_\p{L}+)+/gu, '#$&'));

Upvotes: 1

Related Questions