Replacing% 1 and% 2 in my javascript string

Let's say that in my javascript code there is the following line:

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

Now I would like to add something instead of% 1 and% 2 in the line above. I can do:

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

I wonder if there is a better way to do this than calling the replacement function 2 times.

Thanks.

+4
source share
3 answers

How about a little format helper? This is 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

+15
source

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); 
0
source

This is meant as a complex comment on elclarns great answer suggesting these alternatives:

  • May be written as String.prototype
  • You can use arguments

Function can be changed 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 
0
source

Source: https://habr.com/ru/post/1479107/


All Articles