PDA

Click to See Complete Forum and Search --> : replace function???


Padrino
Mar 21st, 2001, 12:16 PM
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???

harsoni
Mar 21st, 2001, 01:55 PM
You can use match and replace functions in javascript..

Sonia

Mark Sreeves
Mar 22nd, 2001, 06:42 AM
The built in replace function but it onlt seems to replace the first 'o'


htmlcontent= htmlcontent.replace('o','i');




this works though:

<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>

Padrino
Mar 22nd, 2001, 07:44 AM
thankz :) it works!

billrogers
Mar 23rd, 2001, 08:36 AM
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

Mark Sreeves
Mar 26th, 2001, 01:22 AM
billrogers

That explains a lot!

I saw an example using the built in replace function but it didn't explain the switches.

Thanks

billrogers
Mar 26th, 2001, 08:26 AM
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.

tadeus
Aug 11th, 2003, 06:59 PM
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