satriabajakan satriabajakan - 21 days ago 11
Javascript Question

How to Replace Text With Split (_)

I know this code:

str1 = str1.replace(/_A/g, '<span>A</span>');


But it was too bad to replace a lot of different words.

So, I have a sentence that there is
(_)
behind the letter. For example
_A _B _C

Well, is there a simple way to change that?

For example,
_A
replaced with
<span>A</span>

Answer

Use \w+ for word match in regex and add modifier g for the global match.

str1 = str1.replace(/_(\w+)/g, '<span>$1</span>'); // use captured value within the replace pattern

var str = '_A _B _C';
console.log(str.replace(/_(\w+)/g, '<span>$1</span>')) 


UPDATE : To match the string like _A/B and _A#B you need to use character class with those special symbols.

str1 = str1.replace(/_([\w\/#]+)/g, '<span>$1</span>'); // use captured value within the replace pattern

var str = '_A _B _C _A/B  _A#B';
console.log(str.replace(/_([\w\/#]+)/g, '<span>$1</span>'))


FYI : The \w also includes _ if you want to avoid that then use negated character class [^\W_] instead