views:

52

answers:

1

Hello,

I want to write a script which adds in a string a backslash () everytime it finds a quotation marks or \r. It works but for " and ', but I don't know how to write it for \r. Could anyone help me? THANKS

<script type="text/javascript">
var test="Let\'s test if this \"works\" properly";
var escapedString = test.replace(/(['"])/g, "\\$1");
document.write(escapedString);
</script>

Output: Let\'s test if this \"works\" properly

A: 

Just include the \r in your square-bracket expression.

<script type="text/javascript">
var test="Let\'s test if this \"works\" properly";
var escapedString = test.replace(/(['"\r])/g, "\\$1");
document.write(escapedString);
</script>

EDITED TO ADD EVENT-BASED INPUT SOLUTION:

Apparently what you really mean is you want to know how to add an event listener to an input and have it work on keypress.

<input type="text" onkeyup="keyUpHandler(event)"/>

And handle it like this:

function keyUpHandler(event) {
  event = event || window.event; // allowing for IE
  var kc = event.keyCode;
  var re = /[\r\n]+/;
  if kc.match(re) {
    // statements
  }
}

Try something like that. Hope this helps.

Robusto
Thank you but it doesn't work. It is my fault, I didn't explain it properly. When I say "\r" I really mean when you press ENTER (new line). What you suggested works when it is written literally "\r", but no when a new line is found. Can you help me? THANKS once again.
Arturo
Then what you're asking is really about how to listen for the `onkeyup` event and writing a handler for that. Added a section in my answer above to get you started.
Robusto
Thank you very much for your help!!
Arturo
@Arturo: You're quite welcome. If this answer helped you, consider upvoting it or accepting it by clicking the checkmark. This will boost your reputation and make it more likely people will respond to your future questions.
Robusto