|
-
Mar 21st, 2001, 01:16 PM
#1
Thread Starter
Member
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???
-
Mar 21st, 2001, 02:55 PM
#2
Lively Member
You can use match and replace functions in javascript..
Sonia
-
Mar 22nd, 2001, 07:42 AM
#3
Frenzied Member
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>
-
Mar 22nd, 2001, 08:44 AM
#4
Thread Starter
Member
Thank you!
thankz it works!
-
Mar 23rd, 2001, 09:36 AM
#5
Hyperactive Member
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
-
Mar 26th, 2001, 02:22 AM
#6
Frenzied Member
billrogers
That explains a lot!
I saw an example using the built in replace function but it didn't explain the switches.
Thanks
-
Mar 26th, 2001, 09:26 AM
#7
Hyperactive Member
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.
-
Aug 11th, 2003, 06:59 PM
#8
New Member
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
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|