1

I have a text where I want to replace all the letters "A" with different values. I have an array ["b", "c", "d"] and I want to replace first found "A" with "b", the second one with "c" and so on. Anyone, please help. Here is what I am trying and what I get

   var str = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
		var a = ["b", "c", "d"];
		var c = str.replace(/a/g, a);
		console.log(c);

2
  • 1
    Does this answer your question? Replace multiple strings with multiple other strings Commented Dec 27, 2019 at 16:11
  • @AndersonGreen no I want to replace 1 string with different strings Commented Dec 27, 2019 at 16:12

2 Answers 2

2

You could take a closure over the index and increment the index and adjust with the lenght of the array.

var str = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
    a = ["b", "c", "d"];
    c = str.replace(/a/g, (i => () => a[i++ % a.length])(0));

console.log(c);

Sign up to request clarification or add additional context in comments.

Comments

1

You can just keep an index and adjust it every time it is used. (I capitalized the values to easily find them in the result.

var str = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";

var a = ["b", "c", "d"];
var index = -1;
var c = str.replace(/a/g, function(){
  return a[++index % a.length].toUpperCase();
});
console.log(c);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.