In JS Development, we may encounter such a problem
When you need to dynamically insert HTML tags through JS
In particular, when encountered a large number of variable stitching, quotation marks layer nesting situation, there will be escape character problems, often error
Let's look at an example.
Run a direct error
Next, change the escape character \ "to \" try
After running, the discovery still does not display correctly
This code is not only seemingly messy, difficult to maintain, the key is very error-prone
Next we begin to encapsulate the format string method
String.js
(function () {
///<summary>
///quote escape symbol
///</summary>
string.escapechar = ' \ ';
<summary>
///Replace all strings
///</summary>
///<param name= "Searchvalue" > Retrieve value </param >
///<param name= "Replacevalue" > Replacement value </param>
String.prototype.replaceAll = function ( Searchvalue, Replacevalue) {
var regExp = new RegExp (Searchvalue, "G");
Return This.replace (REGEXP, Replacevalue);
}
<summary>
///formatted string
///</summary>
String.prototype.format = function () {
var RegExp =/\{(\d+) \}/g;
var args = arguments;
var result = This.replace (RegExp, function (m, I, O, n) {return
args[i];
});
Return Result.replaceall ('% ', String.escapechar);
}
) ();
Pass the variable value through the placeholder, replace the quote escape character with%, the code is concise a lot, also very convenient maintenance, the probability of the error is also much smaller
Look at the test results
The test results are correct and the parameter values are also correctly received in the Click events
Case Download Address: Http://wd.jb51.net:81//201612/yuanma/StringFormat_jb51.rar
The above is the entire content of this article, I hope the content of this article for everyone's study or work can bring some help, but also hope that a lot of support cloud Habitat community!