简体   繁体   English

在JavaScript中正确处理mongodb时转义单引号

[英]in javascript properly escape single quote when dealing with mongodb

To use a tts method in my javascript code I wrote this code: 要在我的JavaScript代码中使用tts方法,我编写了以下代码:

i(class="btn-left-margin fa fa-volume-down fa-2x speak-task", onclick=`responsiveVoice.speak(${word.rq}, "French Female");return false;`)

and the French sentence is saved to mongodb as "...jusqu'à...", that is it has a single quote. 法语句子以“ ...jusqu'à...”的形式保存在mongodb中,即单引号。

This breaks the code obviously and I get: 这显然破坏了代码,我得到:

SyntaxError: missing ) after argument list

How to properly escape to prevent this and similar cases to happen? 如何适当逃脱以防止发生这种情况和类似情况? I remember "validate input, escape output" but I don't know how! 我记得“验证输入,转义输出”,但我不知道该怎么做!
Edit 编辑
If I remove the single quote and have it as "...jusqu à...", it works fine. 如果我删除单引号并将其作为“ ... jusquà...”,则可以正常工作。 I just found out that I don't know how properly escape all javascript related characters before saving to mongodb. 我刚刚发现,在保存到mongodb之前,我不知道如何正确地转义所有与JavaScript相关的字符。
By reading forum here , I solved my case with this improvement: 通过在这里阅读论坛,我通过以下改进解决了我的问题:

onclick=`let x="${word.ea}".replace(/['"]+/g, ' ');speakEn(x)`

but I think there must be some best practice for escaping the code in JS that I don't know, which will escape out all special characters when publishing text from mongodb (like "<" and ">", etc.). 但是我认为必须有一些最佳实践来转义我不知道的JS中的代码,当从mongodb中发布文本时(例如“ <”和“>”等),该代码会转义所有特殊字符。 I first thought it could be escape() method, but it happens not to be the one and even deprecated. 我最初以为它可以是escape()方法,但是它恰好不是一个甚至被弃用的方法。

这段代码解决了我的问题:

onclick=`let x="${word.ea}".replace(/['"]+/g, ' ');speakEn(x)`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM