我在 javascript 中有这个文本:
'This is a %{component} with a %{value}'
我应该%{\w+}
用<span>word</span>
最终结果应如下所示:
'This is a <span>component</span> with a <span>value</span>'
我在 javascript 中有这个文本:
'This is a %{component} with a %{value}'
我应该%{\w+}
用<span>word</span>
最终结果应如下所示:
'This is a <span>component</span> with a <span>value</span>'
正如已经写好的使用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>"
这是你想要的?
<!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>
您可以使用javascript / jquery 中的正则表达式来做到这一点。看看这里:http ://de.selfhtml.org/javascript/objekte/regexp.htm