简体   繁体   中英

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. 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.

How can i solve this problem using javascript? Advance thanks for help.

Use PHP function htmlspecialchars() .

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

And here's JavaScript equivalent:

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

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

Source: HtmlSpecialChars equivalent in Javascript?

There is an awesome inbuild function in Javascript. escape() funtion.

<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

This can also be achieved by using Prototype in 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

Hope it helps! :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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