SoFunction
Updated on 2025-03-03

JavaScript simulates C# formatted strings

JS simulates C# string formatting operations

/***
 ** Function: String formatting replacement operation
 ***/
 = function () {
 var args = arguments;
 return (/\{(\d+)\}/g,
 function (m, i) {
  return args[i];
 });
}

js implements a string processing function format() similar to C#:

Those who are familiar with C# should know that there is a method like format(). Let’s imitate it below and implement this function in JavaScript.

The code example is as follows:

=function(args){ 
 if(>0){ 
 var result=this; 
 if(==1&&typeof(args)=="object"){ 
  for(var key in args){ 
  var reg=new RegExp("({"+key+"})","g"); 
  result=(reg, args[key]); 
  } 
 } 
 else{ 
  for(var i=0;i<;i++){ 
  if(arguments[i]==undefined){ 
   return ""; 
  } 
  else{ 
   var reg=new RegExp ("({["+i+"]})","g"); 
   result = (reg, arguments[i]); 
  } 
  } 
 } 
 return result; 
 } 
 else{ 
 return this; 
 } 
}
var fistStr="{0}Welcome,I hope everyone can get what they want{1}";
var secondStr="{webName}Welcome,I hope everyone can get what they want{favoriate}";
var firstOut=("","thing");
var secondOut=({webName:"",favoriate:"thing"});
(firstOut);
(secondOut); 

The above code implements the effect we want. Let’s introduce its implementation process below:

1. Implementation principle:

The principle is relatively simple, so I will tell you a long story short here. For details, please refer to the code comments. Use regular expressions to find the strings to be replaced, and then replace these strings with the specified content. In the code, some of the specified contents are direct string quantities, while others are the attribute values ​​of the object.

2. Code comments:

=function(args){{}), add an instance method format to the String object through the prototype object. This method is used to process strings.

(>0), if the number of passed parameters is greater than 0.

result=this, assign the reference of this to the variable result.

(==1&&typeof(args)=="object"), used to determine whether the passed parameter is a direct quantity of an object.

(var key in args), iterates over the properties in the object's direct quantity.

reg=new RegExp("({"+key+"})","g"), used to match the specified string.

=(reg,args[key]), replace the matching string with the attribute value.

{}, if the object is passed is not a direct quantity.

(var i=0;i<;i++), traverse the passed parameters.

(arguments==undefined), if undefined, returns an empty string.

reg=new RegExp("({["+i+"]})","g"), used to match the specified string.

=(reg,arguments), replace.

result, return the replaced string.

this, if no argument is passed, returns the string itself.