JavaScript String Common Operations Summary (very practical) _javascript tips

Source: Internet
Author: User
Tags lowercase

String interception

1. Substring ()

xString.substring(start,end)

SUBSTRING () is the most commonly used method of string interception, which receives two parameters (arguments cannot be negative), the start and end positions to intercept, and returns a new string whose contents are all characters from start to end-1. If the ending argument (end) is omitted, it is intercepted from the start position to the last.

Let str = ' www.jeffjade.com '
console.log (str.substring (0,3))//www
console.log (str.substring (0))// www.jeffjade.com
Console.log (str.substring ( -2))//www.jeffjade.com (negative is considered 0)

2. Slice ()

stringObject.slice(start, end)

The slice () method is very similar to the substring () method, and the two arguments passed in also correspond to the starting and ending positions respectively. The difference is that the arguments in slice () can be negative, and if the argument is a negative number, the argument sets the position from the tail of the string. In other words,-1 refers to the last character of the string.

Let str = ' www.jeffjade.com '
console.log (Str.slice (0, 3))//www
console.log (str.slice ( -3,-1))/CO
Console.log (Str.slice (1,-1))//www.jeffjade.co
Console.log (Str.slice (2, 1))//' (returns an empty string, start must be less than end)
Console.log (Str.slice (-3, 0))//' (returns an empty string, start must be less than end)

3. substr ()

stringObject.substr(start,length)

The substr () method extracts a specified number of characters from the start subscript in a string. The return value is a string containing the length character starting at the start of the Stringobject, including the character to start. If length is not specified, the returned string contains the character ending from start to Stringobject. In addition, if start is a negative number, it is calculated from the tail of the string.

Let str = ' www.jeffjade.com '
console.log (Webstr.substr (1, 3))/ww.
Console.log (webstr.substr (0))//www.jeffjade.com
Console.log (Webstr.substr ( -3, 3))//COM
console.log ( Webstr.substr ( -1, 5))//m (with a larger target length, whichever is the actual interception length)

4. Split ()

str.split([separator][, limit])

separator Specifies the character (string) to use to split the string. Separator can be a string or regular expression. If separator is omitted, an array of the entire string is returned. If separator is an empty string, STR returns the array form of each character in the original string.

Limit an integer that limits the number of segmented fragments returned. The split method still splits each matching separator, but the returned array will only intercept up to limit elements.

Let str = ' www.jeffjade.com '
str.split ('. ')//["www", "jeffjade", "com"]
str.split ('. ', 1)//["www"]
Str.split ('. '). Join (')//wwwjeffjadecom

In other words, this function is really good, and many times the requirement for character interception is dependent on a character, and the above three functions need to know where they are. We can certainly use indexOf and other methods to obtain, it is obviously very cumbersome, and the use of split is more easily.

Find class methods

1. IndexOf () & Includes ()

stringObject.indexOf(searchValue,fromIndex)

IndexOf () is used to retrieve the first occurrence of the specified string value in the string. It can receive two parameters, Searchvalue represents the substring to find, Fromindex indicates the start position of the lookup, and the omitted words are retrieved from the start position.

Let str = ' www.jeffjade.com '
console.log (Str.indexof ('. '))//3
Console.log (Str.indexof ('. ', 1))//3
Console.log (Str.indexof ('. ', 5))//
Console.log (Str.indexof ('. ', 12))//-1

Although IndexOf () is used to retrieve the first occurrence of a specified string value in a string, many times it is used to determine whether a specified string exists in the string;

if (Str.indexof (' yourspecifiedstr ')!==-1) {
//do something
}

Be aware that in such a scenario, the includes () in the ES6 language is much more elegant; the includes () method is used to determine whether a string is contained in another string and returns False if it returns true.

str.includes(searchString[, position])

SearchString the substring that will be searched. Position optional. Searches for a substring starting at which index of the current string; The default is 0. It should be noted that the includes () is case-sensitive.

' Blue Whale '. Includes (' Blue '); Returns false
' Joe Chobscho master '. Includes (' Jobs ');//Returns True
if (str.includes (' yourspecifiedstr ')) {
/ /Do something (is it more humane to write?) Yeah, this is a more humane era.)
}

2. LastIndexOf ()

stringObject.lastIndexOf(searchValue,fromIndex)

The LastIndexOf () syntax is similar to indexof (), which returns the last occurrence of a specified substring value, which is retrieved sequentially from the forward.

Let str = ' www.jeffjade.com '
console.log (Str.lastindexof ('. '))//
Console.log (Str.lastindexof ('. ', 1))//- 1
console.log (Str.lastindexof ('. ', 5))//3
Console.log (Str.lastindexof ('. '))//
search ()
Stringobject.search (substr)
Stringobject.search (regexp)

The search () method retrieves the substring specified in the string, or retrieves a substring that matches the regular expression. It returns the starting position of the first matching substring, or 1 if there is no match.

Let str = ' www.jeffjade.com '
console.log (Str.search (' W '))//0
Console.log (str.search (/j/g))//4
Console.log (Str.search (/\./g))//3

Match () method

stringObject.match(substr)
stringObject.match(regexp)

The match () method retrieves the specified value within a string, or finds a match for one or more regular expressions.

If the argument passes in a substring or a regular expression that does not have a global match, the match () method performs a match from the start position and returns null if no match is made to the result. Otherwise, an array is returned, and the No. 0 element of the array holds the matching text, and in addition, the returned array contains two object properties index and input, representing the starting character index and the Stringobject reference (that is, the original string) of the matched text.

Let str = ' #1a2b3c4d5e # ';
Console.log (Str.match (' A ')); Returns null
console.log (str.match (' B '));//Return ["B", Index:4, Input: "#1a2b3c4d5e #"]
Console.log (Str.match (/b/) ); return ["B", Index:4, Input: "#1a2b3c4d5e #"]

If the argument passes in a regular expression with a global match, match () matches from the start position multiple times until the end. If there is no match to the result, NULL is returned. Otherwise, an array is returned that holds all the required substrings, and there are no index and input properties.

Let str = ' #1a2b3c4d5e # '
console.log (Str.match (/h/g))//return null
console.log (Str.match (/\d/g))//Return ["1", "2", "" 3 "," 4 "," 5 "]

Other methods

Replace () method

stringObject.replace(regexp/substr,replacement)

The replace () method is used for string substitution operations, which can receive two parameters, which are substituted substrings (which can be regular) and the text to be replaced.

If the first argument passes in a substring or a regular expression that does not have a global match, the Replace () method will only make one substitution (that is, replace the front one) and return the result string after the replacement.

Let str = ' www.jeffjade.com '
console.log (str.replace (' W ', ' W '))//Www.jeffjade.com
Console.log (Str.replace ( /w/, ' W '))//Www.jeffjade.com

If the first argument passes in a global matching regular expression, replace () replaces the substring that matches the criteria multiple times, and finally returns a result string that has been replaced multiple times.

Let str = ' www.jeffjade.com '
console.log (str.replace (/w/g, ' W '))//WWW.jeffjade.com
toLowerCase () & toUpperCase ()
stringobject.tolowercase ()
stringobject.touppercase ()

The toLowerCase () method converts uppercase letters in a string to lowercase, and the toUpperCase () method converts lowercase letters in the string to uppercase.

Let str = ' www.jeffjade.com '
console.log (Str.tolowercase ())//www.jeffjade.com
Console.log (str.touppercase ())//WWW.JEFFJADE.COM

Template string

This is also the new syntax introduced by ES6 to solve the crappy problem of the traditional output string template, its powerful function, the design of the intimate, it is really a great satisfaction, as good as the drought of the general well-being of the rain. Moreover, in today's MVVM front-end frame of the era, the use of ES6 grammar is not to worry about the compatibility of their own stature, to shape the Dom Template is even more powerful, it is fondle admiringly.

For her use, Nanyi in the ECMAScript 6 entry has a detailed description and examples, this is not to repeat. Just understand that we can operate like this.

function Nciefunc () {return
"Sihai Nobody to Sunset";
}
var Niceman = "Chen Yin-ke";
var jadetalk = ' life recognization into today \ ${nciefunc ()}, the
language out of the ${niceman} "memories home."
'
console.log (Jadetalk)

Running, the Chrome Console output results are as follows:

Life recognization into today
The sunset is no one on the seas,
Chen Yin-Chen's "Memories of the former house."

Combining its method

Take a closer look at the string APIs provided by JavaScript, or there are a lot of, some discarded, and there will be in the future version will come out, many of which are useful, such as: CharAt (x), charCodeAt (x), concat (v1, v2,...), fromCharCode (c1, C2,...) and so on, as well as ES6 extension of the string, such as the string's traversal interface, repeat () and so on, this can be seen in es6-string, here is not much to repeat.

In actual code production, it is often necessary to use these basic methods to produce a set of boxing to solve their needs. It is obvious that by virtue of the prototype attribute, the custom-made method of boxing will be placed on a String object, and then it is daylight. This step is to see a person like, here throw one or two paragraphs, to lead the big Jade.

String inversion

String.prototype.reverse = function () {return
this.split ('). Reverse (). Join (")
}

Remove Blank Lines

String.prototype.removeBlankLines = function () {return
this.replace (/(\n[\s\t]*\r*\n)/g, ' \ n '). Replace (/^[\n\r \n\t]*| [\n\r\n\t]*$/g, ']
}

String Conversions to arrays

1, into a one-dimensional array

The scene is based on a substring of the transformation, the direct use of split is good; if the conversion rules are not uniform, then please ask yourself for more blessings.

Let Str = ' Chen Yin, Lu Xun, Qian Zhongshu, Hu Shi, Wang Guowei, Liang Qichao, Wu, Ji xianlin ' let
hallalloffamearr = Str.split (', ')
Console.log (Hallalloffamearr)
//["Chen Yin-chen", "Lu Xun", "Qian Zhongshu", "Hu Shi", "Wang Guowei", "Liang Qichao", "WU", "Ji Xianlin"]

2, into a two-dimensional array

String.prototype.removeBlankLines = function () {return
this.replace (/(\n[\s\t]*\r*\n)/g, ' \ n '). Replace (/^[\n\r \n\t]*| [\n\r\n\t]*$/g, ']
}
String.prototype.strTo2dArr = function (Firstsplit, secondsplit) {
var contentstr = This.removeblanklines (),
Contentstrarr = Contentstr.split (firstsplit),
Resultarr = Contentstrarr.map ( Element) => {return
element.split (secondsplit)
}) return
Resultarr
}
var str = '
Among insects bells out in the distance, Yiyi shadow million Raven hidden.
life recognization into today, Sihai no one to the sunset.
Broken mountains and rivers to meet the victory, the rest of the years sent desolate.
Pine Mensong Back again dream, and recognized as hometown.
'
console.log (Str.strto2darr (' \ n ', ', ')]

Running, the output results are as follows:

[[' Among insects bells out of the distance ', ' Yiyi Shadow million Raven hidden. ' ],
[' Life recognization into today ', ' no one on the sunset. ' ],
[' Broken mountains and rivers to win ', ' the rest of the years sent desolate. ' ],
[' Pine Mensong Back Again dream ', ' and recognize a hometown. ' ] ]

The above is small set to introduce JavaScript string Common operation summary (very practical), I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

Related Article

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.