1

var str = 'test TEST';

How to get str = '<span class="red">test</span> <span class="red">TEST</span>' in return.

Thanks a lot.

2
  • Since the spaces won't show up as red, there's no real difference between <span class="red">test Test</span> and your result? Why not just wrap the string with the span stuff? Commented Nov 13, 2010 at 1:58
  • if string is test love test Commented Nov 13, 2010 at 2:15

3 Answers 3

2

The following will work for words composed of characters matched by \w, which are a-z, A-Z, 0-9 and _. This means, for example, that it will fail for words containing accented characters, but will work fine for your example.

var str = 'test TEST';
var highlighted = str.replace(/([\w]+)/g, '<span class="red">$1</span>');
Sign up to request clarification or add additional context in comments.

Comments

0

Something like:

str.replace(/(\w+) (\w+)/, '<span class="red">$1</span> <span class="red">$2</span>') 

should work.

Comments

0

You can get all fancy with REGEX and such but it is just a simple string replace.

var tt = "<span class='red'>test</span>"
var TT = "<span class='red'>TEST</span>"

str = str.replace("test", tt).replace("TEST", TT);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.