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 derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

replacing strings

Status
Not open for further replies.

Rydel

Programmer
Joined
Feb 5, 2001
Messages
376
Location
CZ
I have a large VBScript script which extensively uses REPLACE function (to replace substring inside a string with some other substring). I am translating it into JavaScript, so that it could execute in Netscape as well (including older version like NN4 and maybe even NN3). What would you recommend? Is there sucha thing in JS?
Thanks in advance!
Rydel :-)
---
---
 
Rydel,

You can use the
Code:
String.replace
method. An example:

Code:
foo = "foo";           // a string literal
regexp = /foo/;        // a regexp literal
replacement = "bar";   // a string literal
alert( "Before: " + foo );
foo = foo.replace( regexp, replacement );
alert( "After: " + foo );

Hope this helps, cheers NEIL s-)

 
You could even write ur own replace function as follows

function replace(string,text,by) {
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;
}

Hope this helps

;-)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top