1

The array replaceThis is user generated so i cant write constant regex rules.
But how can i create the regex rules?
Any ideas for a nice solution?

var replaceThis = new Array();
replaceThis[0] = ':)';
replaceThis[1] = 'XD';
replaceThis[2] = '-.-';
replaceThis[3] = 'hello world';
replaceThis[3] = ' a ';        
replaceThis[3] = ' B ';                

var message = 'text text :) text text -.- and hello world XD and text a btext B text text';
$.each(replaceThis, function(i)
{
    var regex = new RegExp (" ??? ","gi");
    message = message.replace(regex,'<span class="blue">'+????+'</span>');
});

$('body').append(message+'<hr/>');

Playground: http://jsfiddle.net/s7b3r/2/

Thanks in advance!
Jamie

2
  • What do you need to do? Wrap those strings in a <span>? Commented Dec 16, 2012 at 9:08
  • So you need to escape your regex so that new RegExp ("(:))","gi") does not break? Commented Dec 16, 2012 at 9:18

1 Answer 1

4

Check the working DEMO.

You need to escape the special chars for regex.

String.prototype.escapeRegExp = function() {
  return this.replace(/([.*+?^=!:${}()|[\]\/\\])/g, "\\$1");
}

Then use it like:

$.each(replaceThis, function(i, data){
    var regex = new RegExp(data.escapeRegExp(),"gi");
    message = message.replace(regex, '<span class="blue">$&</span>'); 
});
Sign up to request clarification or add additional context in comments.

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.