Function to Match & Substitute

L

lukes555

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
 
M

Michael Winter

(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, 'g'), values);
}
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top