2

I want to write a javascript function to format message, this is my code:

pattern = "{0},{1}";
args = ["hello", "world"];

pattern.replace(/\{(\d+)\}/g, args["$1"*1]); //$1 stands for \d+, multiply 1 to convert it to a number

I want the result is hello,world, but it is undefined,undefined. so how to change it to make it correct ?

1
  • "$1"*1 returns NaN. Which is not an index on the args array Commented Apr 2, 2014 at 7:09

2 Answers 2

3

Like this:

pattern.replace(/\{(\d+)\}/g, function($0, $1){ 
   return args[$1];
});
Sign up to request clarification or add additional context in comments.

2 Comments

what does $0, $1 mean?
@hiway $0 is just the matched string, $1 being the first match parameter. See the MDN docs for replace: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
0

Check this demo jsFiddle

Regexp Patten

/\{(\d+)\},\{(\d+)\}/g

JavaScript

 pattern = "{0},{1}";
 args = ["hello", "world"];

 pattern.replace(/\{(\d+)\},\{(\d+)\}/g, args);
 //console.log(pattern.replace(/\{(\d+)\},\{(\d+)\}/g, args));

Console Result

hello,world 

1 Comment

But this is hardcoded to two variables. @CD..'s answer handles an infinite amount of parameters

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.