Interesting ways to manipulate JavaScript strings string and array _javascript tips

Source: Internet
Author: User
Tags add numbers string methods javascript array
strings and arrays are common types in program writing, so program languages use string and array as basic types and provide many strings and arrays of methods to simplify manipulation of strings. JavaScript also provides string types and array types, and there are many basic string methods and array methods to easily merge, find, replace, intercept, and so on.

JavaScript, as a scripting language, also provides a mechanism for dynamic parsing, which makes it possible to have some interesting ways of combining array with string operations. These methods may be somewhat eccentric, but they are sometimes better at efficiency, readability and reusability.

Repeating string
Often we want to print a string multiple times (like a split line), we need to repeat a string multiple times, but JavaScript doesn't offer a method like repeat. Of course we can use loops to stitch it up, but we can use the Join method of array in JavaScript to implement repeat
Copy Code code as follows:

function repeat (str, n) {
var arr = new Array (n+1);
return Arr.join (str);
}
Output
//-------

By using the N-gap generated by n+1 array elements and then stitching with the target string, we can get the function of string duplication.
extends the prototype of string to apply the method to all strings
JavaScript object inheritance and method search is based on the prototype chain (prototype chain), all the used strings can be said to inherit from string objects, we can add methods or properties for string object prototype, So the method can be applied to all the objects we use. For example, the repeat method above can be changed to:
Copy Code code as follows:

String.prototype.repeat = function (n) {
var arr = new Array (n+1);
Return Arr.join (this);
};
document.write ('-'. Repeat (21));
Output
//---------------------

Then, by calling the repeat method directly from the string, you get the same result as the top.
This allows us to expand the string method and to manipulate the string, but this "pollutes" the JavaScript string, and when the code is transferred to another file but that file does not get the extension, it may cause the method to be found; Calling the prototype extension method is slightly slower than calling the method directly, because JavaScript first tries to find it in the string object's own method, and then finds the string's prototype method And then maybe in the future our expanded methods (such as repeat) become standard methods, and then using this code will override the standard method and get inconsistent results.

But ignoring these considerations, expanding the JavaScript standard type of prototype will still give programming a lot of traversal.

using array as StringBuilder
In many advanced languages, the plus sign (+) is given more meaning in the operation of strings: an operator that is concatenation of strings. In Java and C #, however, we also know how to do string concatenation frequently, and using the plus sign (+) creates an efficiency problem, so the use of StringBuilder is recommended in this case.

JavaScript also supports the use of a plus sign (+) for string concatenation, so there can be an efficiency problem. However, JavaScript does not provide classes like StringBuilder.

In fact, when using StringBuilder in java,c#, most of us also use the Append method, and rarely use inserts. The good news is that JavaScript array is automatically growing in size, so we can use array to do StringBuilder, and then join an empty string to stitch out the target string.
Copy Code code as follows:

var sb = [];
for (var i = 0; I <=21; i++) {
Sb.push (i);
}
document.write (Sb.join ('));
Output
0123456789101112131415161718192021

In the end is using array to do StringBuilder or direct string stitching, Jsperf has a lot of testcases compare the efficiency of both, but because of the initial value, environment, string length and so on, so the results are different. string concatenation is still possible if the strings are not very large, or you can use multiple plus signs (+), and if you append to the same string variable in different places in your code, it might be better to use array to fit the join.

Find and replace substring with split instead of string
In the operation of strings, it is very common to find out whether a substring exists from a string, then either intercept the string, or replace the substring with another string.

For example, give a filename, depending on the point (.) Split gets the base name and suffix name. Let's take a look at these operations that are implemented using the standard string method:
Copy Code code as follows:

function Getbasename (str) {
var pos = Str.lastindexof ('. ');
if (POS < 0) return str;
Return str.substring (0, POS);
}
function GetExtension (str) {
var pos = Str.lastindexof ('. ');
if (POS < 0) return ";
Return Str.substr (pos+1);
}
var fileName = ' hello_world.js ';
document.write (Getbasename (fileName));
document.write (' <br/> ');
document.write (GetExtension (fileName));
Output
Hello_world
Js

(in addition to substr and substring, JavaScript and slice can be used to get string strings, but also because of too many choices, often let me in the choice of panic, there is a position should not be +1, the negative is how to deal with also let me worried. )

You can also use string split to make an array of strings by using join to turn the array into a string before you see it. For a problem with the filename and extension on the top, we can base the "." Split the file name into various parts, then if the resulting number is greater than 1 (the suffix name exists), then the last element of the resulting number is the file extension:
Copy Code code as follows:

function Getbasename (str) {
var segs = Str.split ('. ');
if (Segs.length > 1) segs.pop ();
Return Segs.join ('. ');
}
function GetExtension (str) {
var segs = Str.split ('. ');
if (segs.length <= 1) return ";
return Segs.pop ();
}

Considering that the file name may contain multiple ".", we still need to use the "." Join back all the parts except the last part.
Seeing that you can split and then join the string, you can think of the argument that we can pass in a different string for the arguments of the two methods, which is the function of replacing string substitution with substring, and it's also a global replacement.
For example, want to replace all the underscore (_) with a horizontal bar (-):
Copy Code code as follows:

var str = ' Hello_from_ider_to_world '. Split ('_'). Join ('-');
document.write (str);
Output:
Hello-from-ider-to-world

Instead of the Replace method of string, this method is somewhat in that it can implement global substitution, and to allow replace to be replaced globally, you need to pass in the regular Expression object (REGEXP) instead of the string as the first argument.

Replace to accept regexp, function as parameters
Many people know that string replace method is used to replace string substrings, or that it can accept regular expressions as the first parameter, and how to replace all occurrences, you must use RegExp and include the global tag.
For example, before the replacement operation, replace should be:
Copy Code code as follows:

var str = ' Hello_from_ider_to_world '. Replace (/_/g, '-');
document.write (str);

Another example is the commonly used trim method, although JavaScript is not provided we can also quickly implement ourselves:
Copy Code code as follows:

String.prototype.trim = function () {
Return This.replace (/^\s+|\s+$/g, "");
};

We know that a very powerful function of a regular expression is the backward reference (back Reference), in fact, the JavaScript replace does not only refer back to the first parameter, but also can be referenced backwards on the replacement string, except that in many places the backslash (\) Add numbers as a sign and JavaScript is marked with a US knife ($) plus a number.
Copy Code code as follows:

var friends = ' Friends of Ider, friend of Angie ';
var result = Friends.replace (/(Friends?) of (\w+)/g, "$ $");
document.write (result);
Output
Ider ' s friends, Angie ' s friend

By quoting backwards in the replacement string, we quickly turned "friend of who who" into "Who's friend". What if it's a little more complicated? No, replace can also accept function as a callback function, where the first argument of the function is a string in the entire match, and each one represents a back reference match, and the return value of the function is the replacement string. So many uses, the function parameters will be expressed in $, $ $. Take a look at an example:
Copy Code code as follows:

var friends = "Friends of mine, friend of her and friends of his";
var result = Friends.replace (/(Friends?) of (\w+)/g,
Function ($, $, $) {
if ($ = ' mine ') $ = ' my ';
return $ + ' + $;
});
document.write (result);
Output
My friends, her friend and his friends

The callback function allows you to implement a number of very responsible string matches. As for efficiency, we will not consider it first.

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.