Finding multiple characters and replacing with JQuery

19,254

Solution 1

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...)

Solution 2

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

Solution 3

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

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

(see my fiddle here: fiddle)

Solution 4

The .serialize() method uses encodeURIComponent to encode all of your fields in a form so you don't have to manually escape strings.

If it's not in a form just use:

description = encodeURIComponent($("#description").val());
Share:
19,254
Rory Standley
Author by

Rory Standley

Updated on June 23, 2022

Comments

  • Rory Standley
    Rory Standley almost 2 years

    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