0

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.

karim_fci
  • 1,212
  • 2
  • 17
  • 36

2 Answers2

1

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?

Community
  • 1
  • 1
Jazi
  • 6,569
  • 13
  • 60
  • 92
0

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! :)

bozzmob
  • 12,364
  • 16
  • 50
  • 73