New String function of Prototype

Source: Internet
Author: User

First, let's create a simple string, and we will often operate on it for example:

VaR string = 'laziness always pays off now .';
String. gsub
The gsub method is similar to the native replace method of JavaScript, but it is more powerful. It accepts two parameters. The first one is the pattern to be searched ). It can be a simple string or a regular expression. The second parameter specifies the content of the style match to be replaced.

Let's start with simple. I don't like spaces, so let's replace spaces with underscores.

String. gsub ('', '_'); // returns" laziness_always_pays_off_now ."
It seems nothing special. We can also use string. Replace (/\ s/g, '_') to accomplish similar things. However, when you realize that the second parameter of gsub can be a function, you will find the gsub luminous point. This function is executed once for each matched part of the string. It accepts the matches array after the style match (the string. Match () method returned by the JavaScript method) as the parameter, and then you return a processed string. Sounds a little confused? Check the Code:

String. gsub (/\ s \ W/, function (MATCH) {return match [0]. touppercase () ;}); // returns "laziness always pays off now ."
Each matching part of the string is passed to the parameter function, which processes the matched part and returns the replaced version. We need to use match [0] to reference the match object because the matching result of the regular expression is returned as an array. The value 0 of the index in the array is the content of the entire match. Starting from the second value, it corresponds to the matching content of each group defined by parentheses in the regular expression: for more information, see regular expression ). If we use grouping in a regular expression, we can get these elements from the matches array.

String. gsub (/(S | f) (\ s)/, function (MATCH) {return match [1]. touppercase () + '-' + match [2];}); // returns "Laziness-always-Pays-Off-now."
String. sub
String. sub is almost the same as string. gsub, but it can accept an optional parameter. Different from all matching content in the default replacement string of gsub, sub only replaces the Matching content specified by the third parameter (1 by default ). Let's look at the original example:

String. sub ('', '_'); // returns" laziness_always pays off now ."
This time, only the first matching space is replaced. If we pass the third parameter and run the following example, we can see the difference:

String. sub ('', '_', 3); // returns" laziness_always_pays_off now ."
In other aspects, String. sub is the same as string. gsub. (TRANSLATOR: it can be seen that gsub is more G than sub, which represents the G mark in the regular expression, which sets all pattern in full-text search ).

String. Scan
The scan method is a simple call to gsub. The input style and an enumeration function are used as parameters. This enumeration function cyclically executes the Matching content.

String. Scan (/\ W +/, alert); // produces 5 alerts: "Laziness", "always", "pays", "off", "now"
Another method is to use scan to obtain an array that matches all the results.

VaR Results = [];
String. scan (/\ W +/, function (MATCH) {results. push (Match [0]. touppercase () ;}); // Results = ['lastwith', 'alway', 'pays ', 'off', 'right']
String. truncate
The purpose of this method is as expected after the name, but there are some small organs (in my opinion) That truncate truncates the string by the number specified by the first parameter,

String. truncate (15); // returns "Laziness alw ..."
It seems to work normally, but it only takes 12 characters instead of the 15 expected ones. This is because it also has an optional second character type parameter, which is attached to the truncated string and also involved in the return length count. The second parameter defaults to "...". The following modifications can satisfy the expected results in the above example:

String. truncate (15, ''); // returns" laziness always"
Template Class
Finally, let's talk about the template class. I think it is a beautiful job. It allows us to construct a string template, where the set variables can be replaced in subsequent code. Like PHP templates or any server template technology we have seen. The default variable replacement style is: # {variable_name }. Here is an example to show how to create a template:

VaR linktemplate = new template ('<a href = "# {href}" >#{ text} </a> ');
You can then call its Evaluate Method and input an object parameter corresponding to the attribute name and the variable to render the result, as shown below:

Linktemplate. evaluate ({href: 'http: // www.google.com ', text: 'The omnipotent one'}); // returns "<a href =" omnipotent one </a>"
Array. It also supports:

VaR arraytemplate = new template ('original: # {0}, sequel: #{1 }');
Arraytemplate. Evaluate (['naked gun', 'naked gun 2 100']); // returns "Original: Naked Gun, sequel: Naked Gun 2 1/2"
Customizing the template variable pattern
With sufficient flexibility, we can further customize our template class. For example, you already have an excellent template, but it is written in PHP's short tag syntax. As a lazy programmer, you naturally do not want to rewrite the template. But don't worry. It is worthwhile to make some effort in the future.

The second optional parameter of the template constructor is a regular expression that defines the variable replacement pattern. The default value is constant template. pattern, which defines the # {Variable} syntax. We can also customize our own variable replacement syntax and try the following code:

Template. phppattern =/(^ |. | \ r | \ n) (<\? = \ S * \ $ (.*?) \ S * \?>) /;
Now, we can apply the PHP template directly, and prototype works magically.

VaR phptemplate = new template ('<Div id = "<? = $ ID?> "Class =" <? = $ Class?> "> <? = $ Content?> </Div> ', template. phppattern );
Phptemplate. evaluate ({ID: 'News', class: ['updated', 'arbitrary ']. join (''), content: '<p> no news is good news... </P> '}); // returns "<Div id =" news "class =" updated arbitrary "> <p> no news is good news... </P> </div>"
If you need ajax to call and return JSON data, this will be very helpful to you. You can create a PHP template loaded on the page as a template object, then execute the evalute method of the template and pass in the JSON object obtained by the Ajax request as the parameter.

Of course, this is recommended only when the PHP template does not include the business/application logic that may carry risks. Remember that any information that javascript can access can be seen by anyone. I recommend that you only use it for simple variable replacement. If you use it in large quantities, be careful.

Although I personally love the PHP template syntax, I still provide a smarty style to explain it:

Template. smartypattern =/(^ |. | \ r | \ n) ({\$ (.*?) \})/;
Note that the custom style must conform to the regular expression structure of template. pattern ). If the structure is not in the (beforepattern) (varsyntax (varname) format, the variables in the template may not be replaced correctly, because it depends on the format to generate the corresponding 1, 2, 3.

Coming full circle
Now, we have shown you the template class. Finally, let's take a look at the tips of string. gsub and string. sub. Their second parameters can also be a template string:

String. gsub (/\ s/, '# {0} _'); // returns "Laziness _ always _ pays _ off _ now ."
Compared to using a function as the second parameter, the index for variable matching corresponds to the matches array index passed to the function. Here is an example:

'Cory Hudson '. gsub (/(\ W +)/, '# {2}, # {1}'); // returns "Hudson, Cory"
Note that the template style does not support defining the style syntax as if the template object was created directly through the constructor. You can only use the ruby syntax, but it is not bad, isn't it?

Translators:
In fact, such features can also be implemented using the native replace method, such:

'Cory Hudson '. Replace (/(\ W +)/g, "$2, $1 ");
Therefore, supported function parameters are powerful for gsub.

Strings can be fun!
The methods provided by prototype to native string objects are quite interesting. They can save you a lot of coding time. In fact, changing parameters make them so flexible.

# JavaScript/ajax Columns

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.