Reputation:
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
Upvotes: 5
Views: 19525
Reputation: 184
You can use | (pipe) to include multiple characters to replace:
str = str.replace(/X|x/g, '');
(see my fiddle here: fiddle)
Upvotes: 2
Reputation: 9933
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
Upvotes: 2
Reputation: 1
you can create function recursive
function replaceBr(){
var val = $("#description").val();
while (val !=(val = val.replace(/\n/g, '<br />')));
return val;
}
thx
Upvotes: 0
Reputation: 682
Try This Put your values in variables and replace.
$(function () {
var s = "str";
var t = "nw str";
alert(s.replace(s, t));
});
Upvotes: 0
Reputation: 4775
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());
Upvotes: 1
Reputation: 150020
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 '''
or '''
if that's what you need...)
Upvotes: 15