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>
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With