-
I want to know if there is a function in Javascript that can replace charater by another one.....ex:
var htmlcontent;
htmlcontent ="hello world";
htmlcontent= replace(htmlcontent,o,i);
alert(htmlcontent);
and I want the alert to show "helli wirld". Is there a function that can do that???
-
You can use match and replace functions in javascript..
Sonia
-
The built in replace function but it onlt seems to replace the first 'o'
Code:
htmlcontent= htmlcontent.replace('o','i');
this works though:
Code:
<HTML>
<HEAD>
<script language="JavaScript"><!--
function replace(string,text,by) {
// Replaces text with by in string
var strLength = string.length, txtLength = text.length;
if ((strLength == 0) || (txtLength == 0)) return string;
var i = string.indexOf(text);
if ((!i) && (text != string.substring(0,txtLength)))
return string;
if (i == -1) return string;
var newstr = string.substring(0,i) + by;
if (i+txtLength < strLength)
newstr += replace(string.substring(i+txtLength,strLength),text,by);
return newstr;
}
function doit()
{
var htmlcontent ="Hello World"
htmlcontent= replace(htmlcontent,'o','i');
alert(htmlcontent);
}
//--></script>
</HEAD>
<BODY>
<form>
<input type=button onClick="doit()" value="click">
</form>
</BODY>
</HTML>
-
Thank you!
-
Regular Expressions
I replied to the post you put in the java forum, but in case you are wondering a better way then marks do this.
Yeah, if you use regular expressions this will be easy.
var myString = "Hello World";
var results = myString.replace(/o/gi,"i");
alert(results);
regexpr is /texttolookfor/g is for globlal, i is for ignore case
-
billrogers
That explains a lot!
I saw an example using the built in replace function but it didn't explain the switches.
Thanks
-
There is also alot of cool and short ways to do regular expressions, for instance they have escape code items built in, like \d will find Digits, you could put a * to find 0 or more occurrences, a plus for 1 or more etc.
I suggest the O'Rielly book on javascript. Not a bad reference book to have.
-
Replace the word
I got a textbox on my webform.
I need to get the word on the left of where the cursor is and replace it with another string, when the user presses Ctrl+Space.
So I think this would be:
a. get to know the user pressed Ctrl+Space.
b. Get the word on the left of the cursor.
c. Replace it with the right string.
Can anyone help me out with at least one of the items?
Thx