Javascript替换字符串中的单词

时间:2013-01-28 08:40:47

标签: javascript regex replace

我在javascript中有这个文字:

'This is a %{component} with a %{value}'

我应该用%{\w+}

替换所有看起来像<span>word</span>的单词

最终结果如下:

'This is a <span>component</span> with a <span>value</span>'

3 个答案:

答案 0 :(得分:2)

如前所述,使用String.replace和RegEx:

var originalString = 'This is a %{component} with a %{value}';
var replacedString = originalString.replace(/%\{(\w+)\}/g, '<span>$1</span>');
// "This is a <span>component</span> with a <span>value</span>"

答案 1 :(得分:1)

这是你在找什么?

<!DOCTYPE html>
<html>
<body>
    <p id="demo">This is a %{component} with a %{value}</p>

    <button onclick="myFunction()">Test</button>

    <script>
      function myFunction()
     {
        var str=document.getElementById("demo").innerHTML; 
        var n=str.replace("%{","< span >").replace("}","< /span >");
        document.getElementById("demo").innerHTML=n;
     }
    </script>
</body> 
</html>

答案 2 :(得分:0)

您可以在javascript / jquery中使用正则表达式执行此操作。 看看这里:http://de.selfhtml.org/javascript/objekte/regexp.htm