简体   繁体   English

如何从javascript输入的文本中转义双引号?

[英]How can I escape double quotes from a text input in javascript?

In a variable, string data is coming from text input like following. 在变量中,字符串数据来自文本输入,如下所示。

var noteStr="<?php echo $_REQUEST["noteStr"];?>";

If user given any double quotes in text input then javascript give an error as expected. 如果用户在文本输入中给了任何双引号,那么javascript会给出预期的错误。 I am not finding a way to use javascript str.replace() in this scenario because before using that on string variable javascript engine generate errors. 我没有找到在这种情况下使用javascript str.replace()的方法,因为在对字符串变量javascript引擎使用它之前会生成错误。

How can i solve this problem using javascript? 如何使用JavaScript解决此问题? Advance thanks for help. 预先感谢您的帮助。

Use PHP function htmlspecialchars() . 使用PHP函数htmlspecialchars()

var noteStr="<?php echo htmlspecialchars($_REQUEST["noteStr"]); ?>";

And here's JavaScript equivalent: 这是等效的JavaScript:

function escapeHtml(text) {
  var map = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#039;'
  };

  return text.replace(/[&<>"']/g, function(m) { return map[m]; });
}

Source: HtmlSpecialChars equivalent in Javascript? 资料来源: HtmlSpecialChars是否等同于Javascript?

There is an awesome inbuild function in Javascript. Javascript中有一个很棒的内置函数。 escape() funtion. escape()函数。

<script>

document.write(escape("Hello friends? Here is the solution!"));

</script>

Will become- 会变成-

Hello%20friends%3F%20Here%20is%20the%20solution%21 

Check out- http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_escape for reference 退房-http ://www.w3schools.com/jsref/tryit.asp? filename = tryjsref_escape以供参考

This can also be achieved by using Prototype in Javascript. 这也可以通过在Javascript中使用原型来实现。 A simple example- 一个简单的例子-

var str = '<div class="article">This is an article</div>';
document.write( str.escapeHTML() );

Will become- 会变成-

 &lt;div class="article"&gt;This is an article&lt;/div&gt; 

Source : http://www.tutorialspoint.com/cgi-bin/practice.cgi?file=prototype_83 来源: http : //www.tutorialspoint.com/cgi-bin/practice.cgi? file= prototype_83

Hope it helps! 希望能帮助到你! :) :)

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

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