0

I would like to replace the occurences of "?" with the values in an array

Example :

var s = "hello ? , my name is ?";

I would like to use something like that

var result= s.replace('?',['john','david']); /** does not work **/
console.log(result) /** "hello john, my name is david" **/
  • Consider using a RegEx as the "needle"? `/\?/gi` https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace – evolutionxbox Apr 06 '20 at 11:16
  • Does this answer your question? [How to replace all occurrences of a string?](https://stackoverflow.com/questions/1144783/how-to-replace-all-occurrences-of-a-string) – Nikhil Ponduri Apr 06 '20 at 11:19
  • 1
    This will replace each '?' with array, not with single name – Tomal Apr 06 '20 at 11:21

1 Answers1

2

It is possible to achieve this by using .replace with a regular expression and a function. You'll also need an outside variable to increment. I called it i.

var s = "hello ? , my name is ?";

var i = 0;
var result = s.replace(/\?/g, function() {
  return ['john','david'][i++];
});

console.log(result);
Niklas E.
  • 1,848
  • 4
  • 13
  • 25