将“直引号”转换为“卷曲行情” [英] Converting ″Straight Quotes″ to “Curly Quotes”

查看:187
本文介绍了将“直引号”转换为“卷曲行情”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用基于Javascript的规则引擎的应用程序。我需要一种方法将常规直引号转换为卷曲(或智能)引号。为 [] 做一个 string.replace 很容易,只有这样才会插入一个案例我想到的最好的方法是用左边的卷曲引号替换第一个引用的引号,用左边的引号替换每个引用的引号。



有没有办法用Javascript完成这个?

解决方案

您可以用左引号替换单词字符前面的所有内容,并用右引号替换单词字符后的所有内容。

  str = str.replace(/(?= \w | $)/ g,“); 
str = str.replace(/(?< = \w | ^)/ g,&#8221;); //如果语言支持look-
//落后。否则,请参见下文。

正如下面的评论所指出的,这不会将标点符号带入帐户,但很容易:

  /(?< = [\\\ w,。?!\)] | ^ )/ g 

[编辑:]对于不支持的语言像Javascript一样支持后视,只要你先替换所有前置的,你有两个选择:

  str = str.replace(// g,&#8221;); //用右边的引号替换其余部分
//或...
str = str.replace(/ \b/ g,&#8221;); //替换单词
//边界后的任何引号右边的引号

(我已经离开了上面的原始解决方案,以防这对使用支持后视的语言的人有帮助)


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?

解决方案

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, "&#8220;");
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(/\b"/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)

这篇关于将“直引号”转换为“卷曲行情”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆