Summary of common operations on JavaScript strings (very practical) and javascript Summary

Source: Internet
Author: User

Summary of common operations on JavaScript strings (very practical) and javascript Summary

String Truncation

1. substring ()

xString.substring(start,end)

Substring () is the most commonly used string truncation method. It can receive two parameters (the parameter cannot be a negative value), which are the start position and end position of the truncation, it returns a new string containing all the characters from start to end-1. If the end parameter is omitted, the end parameter is truncated from the start position until the end.

Let str = 'www .jeffjade.com 'console. log (str. substring (0, 3) // wwwconsole. log (str. substring (0) // www. jeffjade. comconsole. log (str. substring (-2) // www.jeffjade.com (negative values are regarded as 0)

2. slice ()

stringObject.slice(start, end)

The slice () method is very similar to the substring () method. The two parameters passed in correspond to the start position and end position respectively. The difference is that the slice () parameter can be a negative value. If the parameter is a negative value, this parameter specifies the position starting from the end of the string. That is,-1 refers to the last character of the string.

Let str = 'www .jeffjade.com 'console. log (str. slice (0, 3) // wwwconsole. log (str. slice (-3,-1) // coconsole. log (str. slice (1,-1) // www. jeffjade. coconsole. log (str. slice (2, 1) // ''(returns an empty string; start must be earlier than end) console. log (str. slice (-3, 0) // ''(returns an empty string. The start value must be smaller than the end value)

3. substr ()

stringObject.substr(start,length)

The substr () method extracts a specified number of characters starting with the start subscript from a string. The return value is a string that contains length characters starting from the start (including the characters indicated by start) of the stringObject. If length is not specified, the returned string contains characters from start to the end of stringObject. In addition, if 'start' is a negative number, it indicates starting from the end of the string.

Let str = 'www .jeffjade.com 'console. log (webStr. substr (1, 3) // ww. console. log (webStr. substr (0) // www. jeffjade. comconsole. log (webStr. substr (-3, 3) // comconsole. log (webStr. substr (-1, 5) // m (if the target length is large, the actual truncation length prevails)

4. split ()

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

Separator specifies the characters (strings) used to separate strings ). Separator can be a string or regular expression. If the separator is ignored, the array form of the entire string is returned. If separator is an empty string, str returns the array of each character in the original string.

Limit is an integer that limits the number of segments returned. The split method still splits each matched separator, but the returned array only intercepts up to limit elements.

let str = 'www.jeffjade.com'str.split('.') // ["www", "jeffjade", "com"]str.split('.', 1) // ["www"]str.split('.').join('') // wwwjeffjadecom

This function is really easy to use. In many cases, the character truncation requirement depends on a specific character, and the above three functions need to know their location. Of course, we can use indexOf and other methods to obtain the data. Obviously, this is complicated, and it is easier to use split.

Lookup methods

1. indexOf () & includes ()

stringObject.indexOf(searchValue,fromIndex)

IndexOf () is used to retrieve the position where the specified string value first appears in the string. It can receive two parameters. searchValue indicates the substring to be searched, fromIndex indicates the start position of the search, and if it is omitted, retrieval is performed from the start position.

let str = 'www.jeffjade.com'console.log(str.indexOf('.')) // 3console.log(str.indexOf('.', 1)) // 3console.log(str.indexOf('.', 5)) // 12console.log(str.indexOf('.', 12)) // -1

Although indexOf () is used to retrieve the position where a specified string value appears for the first time, it is often used to determine whether a specified string exists in the string; so the code will be like this:

if (str.indexOf('yoursPecifiedStr') !== -1) {// do something}

In this scenario, the des () in ES6 is much more elegant. The des () method is used to determine whether a string is contained in another string, if true is returned, otherwise false is returned.

str.includes(searchString[, position])

The substring to be searched. Position is optional. Searches for substrings starting from the index position of the current string. The default value is 0. It should be noted that des () is case sensitive.

'Blue whare '. des ('Blue '); // returns false 'jobs' jobs '. includes ('jobs'); // returns trueif (str. includes ('yourspecifiedstr') {// do something (is this more user-friendly? Yeah, this is a more humane age )}

2. lastIndexOf ()

stringObject.lastIndexOf(searchValue,fromIndex)

The lastIndexOf () syntax is similar to indexOf (). It returns the last position of a specified substring value, and the retrieval order is forward from the back.

let str = 'www.jeffjade.com'console.log(str.lastIndexOf('.')) // 12console.log(str.lastIndexOf('.', 1)) // -1console.log(str.lastIndexOf('.', 5)) // 3console.log(str.lastIndexOf('.', 12)) // 12search()stringObject.search(substr)stringObject.search(regexp)

The search () method is used to retrieve the specified substring in a string or a substring that matches a regular expression. It returns the starting position of the first matched substring. If no matching substring exists,-1 is returned.

let str = 'www.jeffjade.com'console.log(str.search('w')) // 0console.log(str.search(/j/g)) // 4console.log(str.search(/\./g)) // 3

Match () method

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

The match () method can be used to search for a specified value in a string or to find a match between one or more regular expressions.

If the input parameter is a substring or a regular expression that does not perform a global match, the match () method executes a match from the starting position. If no match is found, null is returned. Otherwise, an array is returned. The 0th elements in the array store the matching text. In addition, the returned array also contains two object attributes: index and input, the index that matches the start character of the text and the reference of the stringObject (that is, the original string ).

Let str = '# 1a2b3c4d5e #'; console. log (str. match ('A'); // return nullconsole. log (str. match ('B'); // return ["B", index: 4, input: "# 1a2b3c4d5e #"] console. log (str. match (/B/); // return ["B", index: 4, input: "# 1a2b3c4d5e #"]

If the parameter is a regular expression with a global match, match () is performed multiple times from the start position until the end. If no matching result is found, null is returned. Otherwise, an array is returned, which stores all the required substrings without the index and input attributes.

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

Other methods

Replace () method

stringObject.replace(regexp/substr,replacement)

The replace () method is used to replace strings. It can receive two parameters. The former is the replaced substring (which can be a regular expression), and the latter is the replaced text.

If the first parameter is a substring or a regular expression that does not match globally, the replace () method will only replace (that is, replace the first ), returns the result string after a replacement.

let str = 'www.jeffjade.com'console.log(str.replace('w', 'W')) // Www.jeffjade.comconsole.log(str.replace(/w/, 'W')) // Www.jeffjade.com

If the first parameter is passed in a globally matched regular expression, replace () will replace the child string that meets the condition multiple times, and finally return the result string that has been replaced multiple times.

let str = 'www.jeffjade.com'console.log(str.replace(/w/g, 'W')) // WWW.jeffjade.comtoLowerCase() & toUpperCase()stringObject.toLowerCase()stringObject.toUpperCase()

The toLowerCase () method can convert uppercase letters in a string to lowercase letters. The toUpperCase () method can convert lowercase letters in a string to uppercase letters.

let str = 'www.jeffjade.com'console.log(str.toLowerCase()) // www.jeffjade.comconsole.log(str.toUpperCase()) // WWW.JEFFJADE.COM

Template string

This is also a new syntax introduced by ES6 to solve the lame problem of traditional output String templates. Its powerful functions and considerate design are indeed extremely satisfying, good as long as the drought meets the general comfort of GaN Lin. What's more, in today's era when MVVM front-end frameworks are popular, ES6 syntax does not have to worry about compatibility issues on its own. It is even more powerful to shape Dom templates.

For her use, Ruan Yifeng has provided detailed descriptions and examples in getting started with ECMAScript 6, and will not go into details here. You only need to understand that we can operate like this. Is it a good question?

Function ncieFunc () {return "";} var niceMan = ""; var jadeTalk = 'life-heavy today \ n $ {ncieFunc ()}, in the format of $ {niceMan}, 'Console. log (jadeTalk)

The Chrome Console output is as follows:

Today
No one in the world sets the sunset,
Let's talk about the old residence of Yi.

Combination Method

Looking at the String Api provided by JavaScript, there are still a lot of, some are somewhat obsolete, and some will be available in future versions; many of them are also quite useful, such: charAt (x), charCodeAt (x), concat (v1, v2 ,...) FromCharCode (c1, c2 ,...) And so on, there are ES6 string extensions, such as the string traversal interface, repeat () and so on, this can be seen in the ES6-string, here is not to go into detail.

In actual code production, you often need to use these basic methods to work out a set of combinations to meet their needs. Obviously, the prototype attribute can be used to place the self-made methods in the String object, and then Dawn. This step depends on your personal preferences. Here, we will throw a second paragraph to introduce the 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, '')}

Convert String to array

1. convert to a one-dimensional array

The scenario is based on the conversion of a sub-string, just use split. If the conversion rules are not uniform, please do it yourself.

Let Str = 'chen xiaotong, Lu Xun, Qian Zhongshu, Hu Shi, Wang Guowei, Liang Qichao, Wu Zhe, Ji Xiaolin 'let hallAllOfFameArr = Str. split (',') console. log (hallAllOfFameArr) // ["Chen Xiaoyun", "Lu Xun", "Qian Zhongshu", "Hu Shi", "Wang Guowei", "Liang Qichao", "wu miao", "Ji xinlin"]

2. convert to 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, secondspseconds) {var contentStr = this. removeBlankLines (), contentStrArr = contentStr. split (firstSplit), resultArr = contentStrArr. map (element) => {return element. split (secondsphistory)}) return resultArr} var str = 'ji Miao bell goes far Fang, Yi linying, Wan fangzang. Today, no one in the world is facing the sunset. The broken mountains and rivers welcome victory, and the remaining years are miserable. He Nian dream of songmen songju, who recognized his hometown as his hometown. 'Console. log (str. strTo2dArr ('\ n ',','))

The output result is as follows:

[['Sounds like a bell out of a distant out', 'yilin-ying-Wan-crow hiding. '],
['Let your life go into today ', 'Nobody cares about the sunset. '],
['Break mountains and rivers to victory ', 'Spare time is miserable. '],
['Song men, Song Ju, He Nian Meng ', and I recognize my hometown as my hometown. ']

The above is a summary of common operations on JavaScript strings (very practical) introduced by xiaobian. I hope it will be helpful to you. If you have any questions, please leave a message for me, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!

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.