5

Lets say I have the following string in my javascript code:

var myText = 'Hello %1. How are you %2?';

Now I would like to inject something in place of %1 and %2 in the above string. I can do:

var result = myText.replace('%1', 'John').replace('%2', 'today');

I wonder if there is a better way of doing than calling 2 times the replace function.

Thanks.

1

3 Answers 3

18

How about a little format helper? That's basically what you need:

function format(str, arr) {
  return str.replace(/%(\d+)/g, function(_,m) {
    return arr[--m];
  });
}

var myText = 'Hello %1. How are you %2?';
var values = ['John','today'];

var result = format(myText, values);

console.log(result); //=> "Hello John. How are you today?"

Demo: http://jsbin.com/uzowuw/1/edit

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

6 Comments

Your approach should allow for %1 to be included using an escape %; for example %%1 ... It may also be useful to allow hashes like %{name} really do have a look at the sprintf here to see a proper implementation that will cover any future permutations diveintojavascript.com/projects/javascript-sprintf
Add a fiddle! This looks great :)
Added fiddle. @AhmedMasud: I usually just do {1} with a slightly different regex. It works for all my needs. But yes, there are libraries for more robust solutions.
@AhmedMasud Although that library is great, the OP really didnt ask for all that. This answer isnt perfect (in the sense that it doesnt have everything you described, nor does it have everything sprintf does), but its a great solution as is.
Thank you all, very instructive.
|
0

Try this sample

function setCharAt(str,chr,rep) {
    var index = -1;
    index= str.indexOf(chr);
    var len= chr.length;
    if(index > str.length-1) return str;
    return str.substr(0,index) + rep + str.substr(index+len);
}

var myText = 'Hello %1. How are you %2?';

var result = setCharAt(myText,"%1","John");
var result = setCharAt(result,"%2","today");

alert(result);

1 Comment

0

This is meant just as a complex comment to elclarns' great answer, suggesting these alternatives:

  1. Can be written as String.prototype
  2. Can use arguments

The function can be altered to

String.prototype.format = function() {
  var args=arguments;
  return this.replace(/%(\d+)/g, function(_,m) {
    return args[--m];
  });
}

And called this way

var result = "I am %1, %2 years old %1".format("Jan",32);
// I am Jan, 32 years old Jan

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.