Common string manipulation functions and usage summary _javascript tips in JavaScript

Source: Internet
Author: User

This example summarizes the common string manipulation functions and usages in JavaScript. Share to everyone for your reference. The specific analysis is as follows:

Recently participated in the front-end intern recruitment of the written test, found that many of the written questions will be the test to string processing, such as where to go to the net-pen questions, Taobao Pen test questions. If you are a regular participant in the written exam or if you are also an experienced one, I believe you are just like me, finding that string processing is one of the most common task types in the front-end recruitment process. These questions have a characteristic, standing in the examiner's angle to consider, it is not you will not, but you can not borrow the XX manual or xx guide or Baidu Google, in a relatively concise way to write the answer. Unfortunately, many developers, of course, I am also one of them, for many often used string processing functions can not remember their usage, always have to turn to the XX manual or xx guide or Baidu Google. The result of this is that these very crucial basic knowledge is not strong enough, in the face of these problems have to use N-level nested for loop to traverse. This is a signal, when you find that you are doing this type of problem, use the For loop too much, then notice, it is likely that you have been biased. Don't underestimate these things, probably in looking for work and normal development play a big role. Well, not much to say, we have to sum up. Inevitably there are omissions, if you happen to be found, welcome to add or DMS.

1. String conversion

String conversion is the most basic requirement and work, you can convert any type of data into a string, you can use any of the following three methods:

var num= 19;
var mystr = num.tostring ();//"19"

You can do the same thing:

var num= 19;
var mystr = String (num);//"19"

Or, just a little simpler:

var num= 19;
var mystr = "" +num; "19"

2, String segmentation

String segmentation, which splits a string into strings, and JavaScript provides us with a very handy function, such as:

var mystr = "I,love,you,do,you,love,me";
var substrarray = mystr. Split (",");
[I, Love, ' you ', ' do ', ' You ', ' love ', ' Me '];
var arraylimited = mystr. Split (",", 3);
["I", "Love", "You"];

The second parameter of Split (), which represents the maximum length of the returned string array.

3. Get string length

The length of the string is often used in development and is very simple as follows:

var mystr = "I,love,you,do,you,love,me";
var mystrlength = mystr.length; 25

4. Query substring

Many people will forget these JavaScript's own methods, or forget their specific usage, which leads to having to nest for loops when doing the problem.

The first function: IndexOf (), which starts at the beginning of the string, finds the return coordinates, and cannot find return-1. As follows:

var mystr = "I,love,you,do,you,love,me";
var index = Mystr.indexof ("You"); 7, based on 0 start, can't find return-1

Second function: LastIndexOf (), which starts at the end of the string, finds the return coordinates, and cannot find return-1. As follows:

var mystr = "I,love,you,do,you,love,me";
var index = Mystr.lastindexof ("You"); 14

The above two functions also receive the second optional parameter, which indicates where to start the lookup.

5. String replacement

Only the string should not stop, the general topic will often encounter to let you find and replace your own string, for example:

var mystr = "I,love,you,do,you,love,me";
var replacedstr = Mystr.replace ("Love", "hate");
"I,hate,you,do,you,love,me"

By default, only the first lookup is replaced, and you want global substitution, and you need to set up the regular global identity, such as:

var mystr = "I,love,you,do,you,love,me";
var replacedstr = Mystr.replace (/love/g, "hate");
"I,hate,you,do,you,hate,me"

More detailed, can refer to: http://www.jb51.net/w3school/js/jsref_replace.htm

6, find the character at the given position or its character encoding value

To find characters at a given location, you can use the following function:

var mystr = "I,love,you,do,you,love,me";
var TheChar = Mystr.charat (8);//"O", also starting from 0

Similarly, one of its sibling functions is to find the character encoding value of the corresponding position, such as:

var mystr = "I,love,you,do,you,love,me";
var TheChar = mystr.charcodeat (8); 111

7. String connection

string concatenation operations can be done simply by using an addition operator, such as:

var str1 = "i,love,you!";
var str2 = "Do,you,love,me?";
var str = str1 + str2 + "yes!";
"I,love,you! Do,you,love,me? Yes! "

Also, JavaScript has its own associated functions, such as:

var str1 = "i,love,you!";
var str2 = "Do,you,love,me?";
var str = str1.concat (STR2);
"I,love,you! Do,you,love,me? "

where the concat () function can have multiple parameters, pass multiple strings, and stitch multiple strings.

8, string cutting and extraction

There are three ways to extract and cut from strings, such as:

First, use Slice ():

var mystr = "I,love,you,do,you,love,me";
var subStr = Mystr.slice (1,5);//", Lov"

The second type uses substring ():

var mystr = "I,love,you,do,you,love,me";
var subStr = mystr.substring (1,5); ", Lov"

The third type uses substr ():

var mystr = "I,love,you,do,you,love,me";
var subStr = mystr.substr (1,5); ", Love"

Unlike the first and second, substr () the second parameter represents the maximum length of the truncated string, as shown in the previous result.

9. String Capitalization conversion

The commonly used conversions are uppercase or lowercase string functions, as follows:

var mystr = "I,love,you,do,you,love,me";
var lowcasestr = Mystr.tolowercase ();
"I,love,you,do,you,love,me";
var upcasestr = Mystr.touppercase ();
"I,love,you,do,you,love,me"

10. String Matching

String matching may require you to have a certain understanding of regular expressions, first look at the match () function:

var mystr = "I,love,you,do,you,love,me";
var pattern =/love/;
var result = Mystr.match (pattern);//[' Love ']
console.log (result. index);//2
Console.log (result.input);// I,love,you,do,you,love,me

As you can see, the match () function is called on the string and accepts a regular argument. To take a look at the second example, use the EXEC () function:

var mystr = "I,love,you,do,you,love,me";
var pattern =/love/;
var result = pattern. EXEC (mystr);//[' Love ']
console.log (result. index);//2
Console.log (result.input);//i , Love,you,do,you,love,me

Simply change the position of the regular and the string, that is, the EXEC () function is called on the regular, passing the string parameter. For the above two methods, the matching result is a string that returns the first matching success, or null if the match fails.

Let's look at a similar method search (), such as:

var mystr = "I,love,you,do,you,love,me";
var pattern =/love/;
var result = Mystr.search (pattern);//2

Returns only the matching subscript found, or 1 if the match fails.

11, string comparison

Compares two strings, compared to rules that are compared in alphabetical order, such as:

var mystr = "Chicken";
var mystrtwo = "egg";
var-i = Mystr.localecompare (mystrtwo); -1-
Mystr.localecompare ("chicken");//0-A-
mystr.localecompare ("Apple");//1

12. Examples

Finally, we look at a front-end pen questions, where to go to the net, I believe many children have done this problem. Title: Write a getsuffix function to get the suffix name of the input parameter, such as input abcd.txt, and return txt. Attach my Answer:

function Getsuffix (file) {return
   File.slice (File.lastindexof (".") + 1,file.length); 
}

Conclusion

There should be more than one function of the string manipulation in JavaScript, but these should all be very common. If there is any need to add, welcome to add! Hope to see these later, and then face the strings of the written examination questions you can very calmly face.

I hope this article will help you with your JavaScript programming.

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.