By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
432,441 Members | 998 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 432,441 IT Pros & Developers. It's quick & easy.

Function to Match & Substitute

P: n/a
Hey Guys,

(Title was too short to be as clear as I would have liked...)

I can remember seeing a function some time ago, but I cannot recall
what it was or how to use it.
I am wanting to have two arrays - oldArray & newArray.
I need a function which I can call so that it will look inside the
specified string ("theString") and replace each instance of each entry
of oldArray with the corresponding entry in new Array.

Example:
theString = "12345678";
oldArray = new Array("1","2","3");
newArray = new Array("One","Two","Three");

theString = theString.XXX(oldArray,newArray);

// theString = "OneTwoThree45678";

Any ideas, suggestions, references?
I tried Googling and had no joy.

Thanks
Luke

Jan 10 '06 #1
Share this Question
Share on Google+
1 Reply


P: n/a
On 10/01/2006 12:32, lu******@gmail.com wrote:
(Title was too short to be as clear as I would have liked...)
It was better than the useless, but all too common, 'Help!'.

[snip]
theString = "12345678";
oldArray = new Array("1","2","3");
newArray = new Array("One","Two","Three");

theString = theString.XXX(oldArray,newArray);

// theString = "OneTwoThree45678";


There is no built-in function that will perform this operation. There is
the String.prototype.replace method, but that doesn't work with arrays.

function replace(string, search, values) {
for(var i = 0, n = search.length; i < n; ++i) {
string = string.replace(new RegExp(search[i], 'g'), values[i]);
}
return string;
}

var theString = '0123456789',
oldArray = [ '1', '2', '3' ],
newArray = [ 'One', 'Two', 'Three' ];

theString = replace(theString, oldArray, newArray);

/* theString = '0OneTwoThree456789' */

Note that replacement order can be important. If you have two search
values where one is a substring of another, the order in which the
replacement occurs will change the result. For instance:

var theString = '100',
oldArray = [ '1', '100' ],
newArray = [ 'One', 'Hundred' ];

theString = replace(theString, oldArray, newArray);

/* theString = 'One00' */

but if:

var oldArray = [ '100', '1' ],
newArray = [ 'Hundred', 'One' ];

theString = replace(theString, oldArray, newArray);

/* theString = 'Hundred' */

Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Jan 10 '06 #2

This discussion thread is closed

Replies have been disabled for this discussion.