JavaScript string Object Common operations summary _javascript tips

Source: Internet
Author: User


Create a String object method
declaration: The method of a string object can also be accessed in all base string values.
Call constructor string ():

 var str = new String ();
 var str = new String (' Hello World ');//Initialize str,str.length = 11;

A string interview asked how to find
1. Access (via index)
(1) charAt () or []
1 arguments, parameter is character position, return character

var strvalue = new String (' Hello World ');
Console.log (Strvalue.charat (1));//e
Console.log (strvalue[1));//e,ie7 and the following versions use this method to return undefined

(2) charCodeAt ()
1 parameters, parameter is character position, return character encoding

var strvalue = new String (' Hello World ');
Console.log (Strvalue.charcodeat (1));//101

2. Find Location
(1) indexOf ()
The first parameter is the specified substring, and the second parameter is the retrieved location. Returns the index, if not found, returns-1

var str = ' Hello World '
str.indexof (' l ');//2, returns the position of the first character found
str.indexof (' l ', 6);//9

(2) LastIndexOf ()
the difference with indexof () is that LastIndexOf () searches for substrings from the end of the string

Character method
1. Extended string
concat ()
Accepts any number of parameters that are used to stitch one or more strings together, returning a concatenation to get a new copy of the string.

var str = new String (' Hello ');
var result = Str.concat (' world ');
Console.log (Result),//hello world
typeof result//"string"

2. Get substring method
Slice (), substr (), substring (), all three methods return a copy of the substring of the manipulated string, and all accept 1 or 2 arguments, before opening [)
(1) slice ()

var str = ' Hello ';
Str.slice (0,2);/"He", the first parameter specifies the position where the string begins, and the second parameter indicates where the string ends
str.slice ( -3);//"Llo", O stands-1, reciprocal,-3 represents the third last L
Str.slice ( -2,-1);//"L", similarly,-2 represents the penultimate second l,-1 represents the first and last O

(2) substring ()

var str = ' Hello ';
Str.substring (0,2);/"He", at this time the parameter meaning with Str.slice (0,2)
str.substring ( -3);//"Hello", the substring () method converts all negative parameters to 0
str.substring ( -3,-2);//"", ditto

(3) substr ()

var str = ' Hello ';
STR.SUBSTR (1,2);//"El", the first parameter specifies the starting position of the string, and the second parameter specifies the number of characters returned
Str.substr ( -3);/"Llo", at which point the parameter meaning is the same as that of Str.slice ( -3)
Str.substr ( -3,-1);/"", The Substr () method converts a negative second argument to 0

SUBSTR () method has a problem in IE when passing a negative value, it returns the original string, IE9 fixes the problem

3. Convert a string to an array
Split ()
Splits the string into multiple substrings based on the specified delimiter (either a string or a RegExp object) and places the result in an array, accepting the optional second argument, specifying the size of the array, and returning the array.

var color = ' Blue,red,orange ';
Color.split ();//["Red,blue,orange"], length 1
color.split (', '),//["Blue", "Red", "orange", length 3
var color = ' Blue-red-orange ';
Color.split ('-');//["Blue", "Red", "orange"], length 3
color.split (', ', 2);//["Blue", "red"]

4. String capitalization conversion
toLowerCase (), toUpperCase ()

var str = ' Hello ';
Str.touppercase ();//"Hello"
str.tolowercase ();//"Hello"

5. Delete String Space method
Trim ()
Deletes all spaces from the front and suffix in the string, and then returns a copy of the result.

var str = ' Hello world ';
Str.trim ()//"Hello World"

6. Pattern matching method of string
(1) match ()
parameters: Only one argument is accepted, either a regular expression or a regexp () object.
Returns: An array. The first item in the array is a string that matches the entire pattern, and each subsequent item (if any) holds the string that matches the regular expression capture group
is essentially the same as calling exec ().

var text = ' cat, bat, Sat, fat ';
var pattern =/.at/;

var matches = Text.match (pattern);
Matches//["Cat"]
matches.input//"cat, Bat, Sat, fat"
matches.index//0

(2) Search ()
parameters: Same as Match () method.
Returns the index of the first occurrence in a string, or 1 if there is no match.
Search () method always look backwards in the past

var text = ' cat, bat, Sat, fat ';
var pattern =/at/;

Text.search (pattern)//1

(3) Replace ()
parameters: Receives two parameters, the first argument can be a RegExp object or a string (this string does not convert to a regular expression), the second argument can be a string or a function.
If the first argument is a string, only the first substring is replaced. The only way to replace all substrings is to provide a regular expression and to specify the global flag (g) flag.
If the second argument is a string, you can also use some special sequence of characters to insert the value from the regular expression operation into the result string.
It can also be a function, and the arguments passed to the function are, in turn, the pattern's match, the pattern's match position in the string, and the original string. In cases where a regular expression defines more than one capturing group, the arguments passed to the function are matched by the pattern, the first capturing the match for the group, and so on, but the last two parameters are the position of the pattern's match in the string and the original string.

character sequence Replace text
$$ $
$& Match substrings in whole pattern
$' SUBSTRING after matching substring
$` Substring before matching string
$n Matches substrings in the nth capturing group, $
$nn Matches the substring of the first nn capturing group, $01

var text = ' xxx-love-xxx ';
var pattern =/xxx/g;

var result = Text.replace (pattern, ' 2 ')
result//"2-love-2"

text.replace (XXX)-\w{4}-(XXX)/g, ' I love You '); /"I Love You"
var text = ' xxx-love-xxx ';
var pattern1 =/xxx/g;

var result = Text.replace (pattern1, ' $$ ')
result//"$-love-$"

var result = Text.replace (pattern1, ' $&2 ')
result//"xxx2-love-xxx2"

var result = Text.replace (pattern1, ' $\ ')
result//"-love-xxx-love-"

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.