Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>

like image 841
satriabajakan Avatar asked Jul 18 '26 04:07

satriabajakan


1 Answers

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

like image 59
Pranav C Balan Avatar answered Jul 20 '26 19:07

Pranav C Balan