Reputation: 43768
Does anyone know how can I replace this 2 symbol below from the string into code?
Upvotes: 0
Views: 2193
Reputation: 273
I recently wrote a typography prettification engine called jsPrettify that does just that. Here's a quotes-only version the algorithm I use (original here):
prettifyStr = function(text) {
var e = {
lsquo: '\u2018',
rsquo: '\u2019',
ldquo: '\u201c',
rdquo: '\u201d',
};
var subs = [
{pattern: "(^|[\\s\"])'", replace: '$1' + e.lsquo},
{pattern: '(^|[\\s-])"', replace: '$1' + e.ldquo},
{pattern: "'($|[\\s\"])?", replace: e.rsquo + '$1'},
{pattern: '"($|[\\s.,;:?!])', replace: e.rdquo + '$1'}
];
for (var i = 0; i < subs.length; i++) {
var sub = subs[i];
var pattern = new RegExp(sub.pattern, 'g');
text = text.replace(pattern, sub.replace);
};
return text;
};
Upvotes: 0
Reputation: 545985
Knowing which way to make the quotes go (left or right) won't be easy if you want it to be foolproof. If it's not that important to make it exactly right all the time, you could use a couple of regexes:
function curlyQuotes(inp) {
return inp.replace(/(\b)'/, "$1’")
.replace(/'(\b)/, "‘$1")
.replace(/(\b)"/, "$1”")
.replace(/"(\b)/, "“$1")
}
curlyQuotes("'He said that he was \"busy\"', said O'reilly")
// ‘He said that he was “busy”', said O’reilly
You'll see that the second ' doesn't change properly.
Upvotes: 1
Reputation: 86186
The hard part is identifying apostrophes, which will mess up the count of single-quotes.
For the double-quotes, I think it's safe to find them all and replace the odd ones with the left curly and the even ones with the right curly. Unless you have a case with nested quotations.
What is the source? English text? Code?
Upvotes: 1