Forum Moderators: open

Message Too Old, No Replies

How to perform this?

         

PHPycho

11:06 am on Jun 28, 2007 (gmt 0)

10+ Year Member



Hello forums!
case:
Suppose i had the following var
var text = "This is my text with 'quotes'";
I want to replace the ' -> \' using some function like replace()
How to perform this?
Thanks in advance to all of you

Fotiman

3:43 pm on Jun 28, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



<script type="text/javascript">
var t = "this is 'some' text";
t = t.replace(/'/g, "\\'");
alert(t);
</script>

The replace take a regexp to search for:

/'/g

That says "do a global search for the '

And the replace it with:

"\\'"

The \ character needs to be escaped by using \\ and then follow that with the ' so the actual string replacement will be \'