我正在寻找一种方法来将用户输入中的引号替换为“更正”的引号。
想法
下面是一个简要说明原理的片段:
对于引号,“正确”的有一个开头的 “
”和一个结尾的 ”
,因此需要以好的方式替换它。
$('#myInput').on("keyup", function(e) {
// The below doesn't work when there's no space before or after.
this.value = this.value.replace(/ "/g, ' “');
this.value = this.value.replace(/" /g, '” ');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="myInput"></textarea>
但上述并不是在所有情况下都有效。
例如,当“引用词”位于句子或一行的最开头或结尾时。
示例
可能的输入(注意,里面是法语!:)):
⋅ 我很“快乐”! Ça y est, j'ai "osé", et mon "âme sœur"était au rendez-vous...
⋅ 标志上写着:“一些文字“一些文字”一些文字。”和“注意这里的空格!”
⋅ "Inc"or "rect"quot"tes should "not be replaced.
⋅ 我说:“如果它也适用于‘单例’,我会更喜欢它!”
正确的输出:
⋅ 我很“快乐”! Ça y est, j'ai “osé”, et mon “âme sœur” était au rendez-vous...
⋅ 牌子上写着:“一些文字“一些文字”一些文字。”和“注意这里的空格!”
⋅ “Inc"or"rect” quot"tes should "not be replaced.
⋅ 我说:“如果它也适用于‘单例’,我会更喜欢它!”
不正确的输出:
⋅ 牌子上写着:“一些文字”一些文字“一些文字。”和[…]
为什么不正确:
→ 引号末尾和结束标记之间不应有空格。
→ 右引号和单词之间应该有一个空格。
→ 单词和左引号之间应该有一个空格。
→ 左引号与其引用之间不应有空格。
需求
在所有这些情况下如何有效且轻松地替换引号?
如果可能的话,我还希望解决方案能够“更正”引号,即使我们在输入整个句子之后 添加引号也是如此。
请注意,我没有(不能)在正则表达式中使用单词分隔符“\b”,因为“不幸的是,重音字符,如“é”或“ü”被视为分词符。” (来源:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions)
当然,如果没有其他解决方案,我会提出一个我认为是单词定界符的列表,并将其用于正则表达式中。但我更希望有一个很好的工作函数而不是一个列表!
任何想法将不胜感激。
最佳答案
It is working for many of the cases, at the exception of when the "word" is at the very beginning or the very end of a sentence or a line.
要解决该问题,您可以交替使用行断言和空格的开头/结尾,捕获它,并在替换中使用它:
this.value = this.value.replace(/(^| )"/g, '$1“');
this.value = this.value.replace(/"($| )/g, '”$1');
交替是 ^|
/$|
。捕获组将是 ""
如果它匹配断言,或者 ""
如果它匹配 sapce。
$('#myInput').on("keyup", function(e) {
this.value = this.value.replace(/'/g, '’');
// The below doesn't work when there's no space before or after.
this.value = this.value.replace(/(^| )"/g, '$1“');
this.value = this.value.replace(/"($| )/g, '”$1');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="myInput"></textarea>
但是,您说过要避免在用户输入时“转义”字符。我不确定您打算在哪里使用它,但是像上面这样的东西几乎从来不是用于解决具有这种描述的问题的方法。
关于javascript - 用引号替换双引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49816069/