Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Apostrophe Replacement

Status
Not open for further replies.

cmcleod

Programmer
Sep 18, 2001
15
US
I am trying to use the following function to replace all occurens of ' in a input box with ''. The function works for alpha characters but hangs when I use the code below.

function replaceChars(entry) {
out = "\'"; // replace this
add = "\'\'"; // with this
temp = "" + entry; // temporary holder

while (temp.indexOf(out)>-1) {
pos= temp.indexOf(out);
temp = "" + (temp.substring(0, pos) + add +
temp.substring((pos + out.length), temp.length));
}
document.subform.text.value = temp;
}

Anyone know how to replace ' with '' using javascript? Thanks.
 
Best way would be to use regular expressions. Here's a sample page to show you what to do. Enter some text (with apostrophes) in the 1st field and click the button.

<html>
<head>
<title>Replace</title>
<script>

function replaceMe() {

var str1=new String(document.forms.f1.t1.value);
rExp=/'/gi;
var str2=new String(&quot;\&quot;&quot;);
document.forms.f1.t2.value=str1.replace(rExp,str2);
}

</script>

</head>
<body>
<form name=&quot;f1&quot;>
Source String : <input type=&quot;text&quot; width=&quot;20&quot; name=&quot;t1&quot;>
<br><br>
Results String : <input type=&quot;text&quot; width=&quot;20&quot; name=&quot;t2&quot;>
</form>

<form>
<input type=&quot;button&quot; value=&quot;Replace Me&quot; onClick=&quot;replaceMe()&quot;;>
</form>

</body>
</html>

Greg.
 
That worked great. How does JavaScript read the /'/gi;?

It seems that is what is making or breaking the code. Thanks.
 
hehe...this is the second time I have posted this link today! this is a great tutorial on regular expressions:

Robert Carpenter
questions? comments? thanks? email me!
linkemapx@hotmail.com
Icq: 124408594
online.dll

AIM & MSN: robacarp
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top