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..
2 Answers 2
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);
Comments
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);
['' + values[i] + ''];- Why the''? And whyvalues[i]?valuesis a string. Should besplt[i]carwith all the words invalues? Or one at the time?replaceStrfunction, that only ever contain one single element? And if you only want to replace one single occurrence of the search term at a time (I’m assuming you do), then why does your regex contain thegmodifier?