Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
225 views
in Technique[技术] by (71.8m points)

javascript - Converting ″Straight Quotes″ to “Curly Quotes”

I have an application which uses a Javascript-based rules engine. I need a way to convert regular straight quotes into curly (or smart) quotes. It’d be easy to just do a string.replace for ["], only this will only insert one case of the curly quote.

The best way I could think of was to replace the first occurrence of a quote with a left curly quote and every other one following with a left, and the rest right curly.

Is there a way to accomplish this using Javascript?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could replace all that preceed a word character with the left quote, and all that follow a word character with a right quote.

str = str.replace(/"(?=w|$)/g, "“");
str = str.replace(/(?<=w|^)"/g, "&#8221;"); // IF the language supports look-
                                             // behind. Otherwise, see below.

As pointed out in the comments below, this doesn't take punctuation into account, but easily can:

/(?<=[w,.?!)]|^)"/g

[Edit:] For languages that don't support look-behind, like Javascript, as long as you replace all the front-facing ones first, you have two options:

str = str.replace(/"/g, "&#8221;"); // Replace the rest with right curly quotes
// or...
str = str.replace(/"/g, "&#8221;"); // Replace any quotes after a word
                                      // boundary with right curly quotes

(I've left the original solution above in case this is helpful to someone using a language that does support look-behind)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...