Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace question marks inside a string with the values of an array?

Given the string 'Hello ?, welcome to ?' and the array ['foo', 'bar'], how do I get the string 'Hello foo, welcome to bar' in a single line of code with JavaScript (possibly with jQuery, Underscore, etc.)?

like image 308
MauroPorras Avatar asked Jan 19 '12 17:01

MauroPorras


People also ask

How do you replace a question mark in a string in Java?

longstring = longstring. replace(replacestring, ""); And it will all work.

How do you replace all values in a string?

String.prototype.replaceAll() The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function to be called for each match. The original string is left unchanged.


1 Answers

var s = 'Hello ?, welcome to ?';
var a = ['foo', 'bar'];
var i = 0;
alert(s.replace(/\?/g,function(){return a[i++]}));
like image 151
Sam Greenhalgh Avatar answered Sep 22 '22 18:09

Sam Greenhalgh