-1

我在 javascript 中有这个文本:

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

我应该%{\w+}<span>word</span>

最终结果应如下所示:

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

3 回答 3

2

正如已经写好的使用String.replace和正则表达式:

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>"
于 2013-01-28T08:49:48.403 回答
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>
于 2013-01-28T08:47:46.783 回答
0

您可以使用javascript / jquery 中的正则表达式来做到这一点。看看这里:http ://de.selfhtml.org/javascript/objekte/regexp.htm

于 2013-01-28T08:43:43.353 回答