-1

I have this text in javascript:

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

I should replace all words that look like %{\w+} with <span>word</span>

The final result should look like:

'This is a <span>component</span> with a <span>value</span>'
Nicolae Rotaru
  • 189
  • 2
  • 11
  • Show us what you've tried first. – Daedalus Jan 28 '13 at 08:41
  • Possible duplicate of http://stackoverflow.com/questions/832257/javascript-multiple-replace – Boaz Jan 28 '13 at 08:45
  • i tried on ruby side, but i realized there are other html tags in the text that should not look like html content, just like plain text,so i decided to do this in javascript side. return value.split("\s").collect{|w|w.match(/%{(\w+)}/) ? "#{w}" : w }.join(" ") – Nicolae Rotaru Jan 28 '13 at 08:45
  • If you already know regex this is all you need https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/replace – elclanrs Jan 28 '13 at 08:46

3 Answers3

2

As already written use String.replace and a 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>"
dan-lee
  • 14,365
  • 5
  • 52
  • 77
1

Is this what you are looking for?

<!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>
catherine
  • 22,492
  • 12
  • 61
  • 85
0

You can do that with regex in javascript / jquery. Have a look here: http://de.selfhtml.org/javascript/objekte/regexp.htm

Thomas1703
  • 1,152
  • 5
  • 16
  • 33