Skip to content Skip to sidebar Skip to footer

Regular Expression For Apostrophes/ Single Quotes With Double

I'm currently working with a regular expression (in Javascript) for replacing double quotes with smart quotes: // ie: 'quotation' to “quotation” Here's the exp

Solution 1:

You can include in quotes all except quotes:

str = str.replace(/"([^"]*)"/ig, "“$1”")

Another option: use non-greedy search:

str = str.replace(/"(.*?)"/ig, "“$1”")

Also I'm not sure that you need to change only single quotes that are at the end of a word. May be it were better to change all of them?

replace(/\'/g, "’");

Solution 2:

You can search for anything not a ". I would also make a lazy match with ? in case you had something like "Hey," she said, "what's up?" as your str:

str.replace(/"([^"]*?)"/ig, "“$1”").replace(/\'\b/g, "’");

Solution 3:

Just to add to the current answers, you are performing a match on [A-Za-z ]* for the double quote replace, which means "match uppercase, lowercase or a space". This won't match It's raining, since your match expression does not contain the single quote.

Follow the advice of matching "anything but another double quote", since with your original regex a string like She said "It's raining outside." He said "really?" will result in She said ”It's raining outside." He said "really?” (the greedy match will skip past the 'inner' double quotes.)

Solution 4:

It's a good idea to limit the spesific characters left and right of the quotes, especially if this occurs in a html file. I am using this.

str = str.replace(/([\n >*_-])"([A-Za-z0-9 ÆØÅæøå.,:;!#@]*)"([ -.,!<\n])/ig, "$1«$2»$3");

In this way, you avoid replacing quotes inside html-tags like href="http.....

Normaly, there is an space left of the opening quote, and another right of the closing quote. In html document, it might be a closing bracket, a new line, etc. I have also included the norwegian characters. :-)

Post a Comment for "Regular Expression For Apostrophes/ Single Quotes With Double"