-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 に答える