Skip to content Skip to sidebar Skip to footer

How To Replace Text With Split (_)

I know this code: str1 = str1.replace(/_A/g, 'A'); But it was too bad to replace a lot of different words. So, I have a sentence that there is (_) behind

Solution 1:

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

Solution 2:

Use the modifiers:

str1 = str1.replace(/_(.*)/g, '<span>$1</span>');

You need to be careful with this as it would take everything till the end.

$(function () {
  $("ul li").each(function () {
    $(this).html(function () {
      return $(this).text().replace(/_(.*)/g, '<span>$1</span>');
    });
  });
});
lispan {background: #eee;}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><ul><li>_A</li><li>_B</li><li>CD</li><li>_E</li><li>_FG</li></ul>

If they are mixed up, you can use the (\w+) word selector instead of (.*) greedy match.

Post a Comment for "How To Replace Text With Split (_)"