Reputation: 73
I made loop for, from split string and try to find some text and replace it by the result of separate string, here for example :
function replaceStr(str, find, replace) {
for (var i = 0; i < find.length; i++) {
str = str.replace(new RegExp(find[i], 'gi'), replace[i]);
}
return str;
}
var str = 'some text contain car and some house contain car, or car contain someone';
var values = "cat,dog,chicken";
splt = values.split(',');
for (i = 0; i < splt.length; i++) {
var find = ['car'];
var replace = ['' + values[i] + ''];
replaced = replaceStr(str, find, replace);
}
console.log(replaced);
//console.log(splt.length);
but the result return zeros
I want find all "car" text and replace it from splited text by comma characters anyone can help me please..
Upvotes: 0
Views: 134
Reputation: 1572
I guess implicitly from your question you want to replace "car" with cat, dog, chicken progressively to achieve this: "some text contain cat and some house contain dog, or chicken contain someone"
So roughly this would be your solution:
var str = 'some text contain car and some house contain car, or car contain someone';
var values = "cat,dog,chicken";
var splt = values.split(',');
var replaced = str;
for (i = 0; i < splt.length; i++) {
replaced = replaced.replace('car', splt[i]);
}
console.log(replaced);
Upvotes: 1
Reputation: 76
hum what is the goal of your replaceStr function ? maybe this is enough :
var str = 'some text contain car and some house contain car, or car contain someone';
var values = "cat,dog,chicken";
splt = values.split(',');
for (i = 0; i < splt.length; i++) {
var find = 'car';
str = str.replace(find, splt[i]);
}
console.log(str);
Upvotes: 2