...

View Full Version : Apostrophe in regular expression



Philip M
03-06-2003, 04:35 PM
I have the following which strips out single and double
quotes ' and " from the user input.

function filter(str) {
noquotes = /\'|"/g;
return str.replace(noquotes, "");
}

This works fine but I am having trouble in modifying the script
to retain single quotes (apostrophes) which do not fall on a word
boundary.

E.g. "Piper's Wood" or 'Piper's Wood' in quotes
to be changed to Piper's Wood
and not Pipers Wood

function filter(str) {
noquotes = /\'|"\b/g;
return str.replace(noquotes, "");
}

does not work.

Would you oblige me, Whammy?

beetle
03-06-2003, 05:29 PM
Ah, who needs Whammy?

return str.replace( /['"](?!\b)/g , "").replace( /([^\w])['"]/g, "$1" );

Philip M
03-06-2003, 06:36 PM
Thank, Beetle.

But your code does not remove the ' or " at the start of the string.

Could you suggest a mod?

beetle
03-06-2003, 06:40 PM
Certainly

return str.replace( /['"](?!\b)/g , "").replace( /([^\w])['"]/g, "$1" ).replace( /^['"]|['"]$/g, "" );

Philip M
03-06-2003, 06:45 PM
That's it Beetle! Thanks a million!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum