Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding multiple characters and replacing with JQuery

I have the following JQuery AJAX call that sends HTML form data to my server side script to deal with. However I currently find line breaks and convert them to <br /> for display in another part of my application. I now need to make sure I am stripping out apostrophes however I am not confident on how to replace multiple characters in one go.

This is the JQuery I use currently before adding this into my AJAX.

description = $("#description").val().replace(/\n/g, '<br />');

Can anyone point me in the right direction?

Thanks

like image 260
Rory Standley Avatar asked Feb 15 '12 09:02

Rory Standley


3 Answers

You don't have to do it in one go in the sense of one call to .replace(), just chain multiple .replace() calls:

description = $("#description").val().replace(/\n/g, '<br />')
                                     .replace(/'/g, '');

(Or replace with '&#39;' or '&apos;' if that's what you need...)

like image 158
nnnnnn Avatar answered Oct 05 '22 02:10

nnnnnn


I agree with nnnnnn that you don't have to do it all in one go though you can use the or | regex operator and use a callback like below, see mdn regex for more details

var foo = '"there are only 10 people in this world that understand binary, 
            \n those who can and those who can\'t"\n some joke';

foo = foo.replace(/\n|"/g, function(str) {
  if (str == '\n') {
    return '<br/>';
  } else {
    return '';
  }
});

document.write(foo);

here is a demo

like image 38
T I Avatar answered Oct 05 '22 01:10

T I


You can use | (pipe) to include multiple characters to replace:

str = str.replace(/X|x/g, '');

(see my fiddle here: fiddle)

like image 28
Gerrit B Avatar answered Oct 05 '22 03:10

Gerrit B