Match @(\w+) and replace in javascript

前端 未结 2 1693
你的背包
你的背包 2021-01-28 12:36

I\'m trying to match @(\\w+) in a div content and remove it.

Here\'s what i\'ve tried : http://jsfiddle.net/mxgde6m7/1/ .

@(\\w+) works , but it doesn\'t replace

相关标签:
2条回答
  • 2021-01-28 13:01

    hwnd is correct that you need to double escape \w in your regular expression.

    var find = '@(\\w+)';
    

    But, you could also make this code much cleaner by defining a regex literal like so -

    var content = document.getElementById('contentbox');
    var result = content.innerHTML.replace(/@(\w+)/g, ' ');
    alert(result);
    

    Doing it this way doesn't require double escaping, as it's not a string.

    0 讨论(0)
  • 2021-01-28 13:02

    Using a RegExp constructor, you need two backslashes \\ in place of each backslash \.

    var find = '@(\\w+)';
    
    0 讨论(0)
提交回复
热议问题