Common JavaScript String Operations

Posted by music_man on Sat, 13 Jul 2019 01:31:07 +0200

JavaScript strings are used to store and process text. So when you write JS code, she always goes hand in hand, when you process user's input data, when you read or set the attributes of DOM objects, when you operate Cookie, when you convert different Date s, and so on, countless; and her many API s, there are always some impulses that people do not want to remember. Since you often search, it's better to turn over your bad pen. By the way, it also reflects the value of the existence of the blog, so there is this summary.

substr

1. substring()

xString.substring(start,end)

substring() is the most commonly used method of string interception. It can receive two parameters (parameters can not be negative), which are the starting and ending positions of interception. It will return a new string whose content is all the characters from start to end-1. If the end parameter (end) is omitted, it means that it is intercepted from the start position to the end.

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

2. slice()

stringObject.slice(start, end)

The slice() method is very similar to the substring() method, and the two parameters it passes in correspond to the start and end positions, respectively. The difference is that the parameter in slice() can be negative. If the parameter is negative, the parameter specifies the position from the end of the string. That is to say, -1 refers to the last character of a 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 the string. Its return value is a string containing length characters starting at the start of stringObject (including the characters referred to by start). If no length is specified, the returned string contains characters from start to the end of stringObject. In addition, if start is negative, it means that it starts at the end 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 (If the target length is large, the actual intercepted length shall be taken as the criterion)

4. split()

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

Separator specifies the character (string) used to split a string. Separator can be a string or regular expression. If separator is ignored, the entire string is returned as an array. If separator is an empty string, str will return the array form of each character in the original string.
Limit is an integer that limits the number of fragments returned. The split method still splits each matching separator, but the returned array only intercepts the maximum 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 to use. Many times the character interception needs to depend on a character, and the above three functions need to know its location. Of course, we can use indexOf and other methods to obtain, which is obviously cumbersome; and split is more easy.

Finding Class Method

1. indexOf() & includes()

stringObject.indexOf(searchValue,fromIndex)

indexOf() is used to retrieve the first occurrence of a specified string value in a string. It can take two parameters, searchValue for the substring to be looked up, fromIndex for the start of the search, and ellipsis for the start.

let str = 'www.jeffjade.com'
console.log(str.indexOf('.'))     // 3
console.log(str.indexOf('.', 1))  // 3
console.log(str.indexOf('.', 5))  // 12
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 the scenario for using indexOf() is to determine whether a specified string exists in the string; therefore, the code will do so:

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

In such a scenario, include () in ES6 is much more elegant; the include () method is used to determine whether a string is contained in another string, if true, or false.

str.includes(searchString[, position])

The substring that searchString will search for. Position is optional. Search for substrings from which index position of the current string; default is 0. It should be noted that include () is case-sensitive.

'Blue Whale'.includes('blue'); // returns false
'Joffon Jobs Job Helper'.includes('Steve Jobs'); // returns true
if (str.includes('yoursPecifiedStr')) {
    // Do something? Yeah, this is a more humane era.
}

2. lastIndexOf()

stringObject.lastIndexOf(searchValue,fromIndex)

The lastIndexOf() grammar is similar to indexOf(), which returns the last occurrence of a specified substring value in a backward-forward search order.

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

3. search()

stringObject.search(substr)
stringObject.search(regexp)

The search() method is used to retrieve a substring specified in a string or a substring matching a regular expression. It returns the starting position of the first matched substring and - 1 if there is no matching.

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

4. match() method

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

The match() method can retrieve a specified value within a string or find a match of one or more regular expressions.

If a substring is passed in the parameter or a regular expression is not globally matched, the match() method performs a match from the start position and returns null if no match is reached to the result. Otherwise, an array will be returned. The zero element of the array stores matched text. In addition, the returned array contains two object attributes index and input, which represent the initial character index of the matched text and the reference of stringObject (that is, the original string).

let str = '#1a2b3c4d5e#';
console.log(str.match('A'));    //Return 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 parameter is passed in a regular expression with a global match, match() matches multiple times from the start to the end. If no result is matched, null is returned. Otherwise, an array is returned, in which all qualified substrings are stored without index and input attributes.

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. It can accept two parameters, the former being substituted substrings (which can be regular) and the latter being substituted text.

If the first parameter passes in a substring or a regular expression that does not match globally, the replace() method replaces only once (that is, replacing the front) and returns the result string that has been replaced once.

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 parameter passes in a globally matched regular expression, replace() replaces the qualified substrings several times, and finally returns the result string that has been replaced many 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 into lowercase letters in strings, and the toUpperCase() method converts lowercase letters into uppercase letters in strings.

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

Template string

This is also a new grammar introduced by ES6 to solve the poor problem of the traditional output String template; its powerful function and intimate design make people feel very satisfied, like a long drought and a good rain. What's more, in the era of MVVM front-end frameworks, ES6 grammar does not need to worry about compatibility issues on its own, and it's a great help to shape Dom Template.

For her use, Ruan Yifeng has a detailed description and examples in the introduction of ECMAScript 6, not to mention here. Just understand that we can operate like this. Is it cool?

function ncieFunc() {
  return "No one in the world is facing the sunset";
}
var niceMan = Chen Yinke;
var jadeTalk = a lifetime of negative energy into today's  n ${ncieFunc()},
Speak out ${niceMan} of "Memory of the Former Residence".
`
console.log(jadeTalk)

Running, the Chrome Console output is as follows:

    Life's Negativity Becomes Today
    There is no one in the world against the setting sun.
    Chen Yinke's Memory of the Former Residence.

Combination method

Looking closely at the String Api provided by JavaScript, there are still quite a few, some abandoned ones, and some will come out in future versions; many of them are useful, such as: charAt(x), charCodeAt(x), concat(v1, v2,... fromCharCode(c1, c2,... ) And so on, there are ES6 extensions to strings, such as the traversal interface of strings, repeat(), and so on, which can be seen in ES6-string, not to mention here.

In the actual code production, many times we need to use these basic methods to play a set of combination punches to meet their needs. Obviously, with the help of prototype attributes, we can put all kinds of self-made boxing methods into String objects, and then dawn. This step depends on personal preferences, here throw out a paragraph or two to attract 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 into arrays

1. Convert to a one-dimensional array

Scenario is based on a substring conversion, just use split; if the conversion rules are not uniform, then please ask for more luck.

let Str = 'internationally known sinologist,Lu Xun,Qian Zhongshu,Hu Shi,Wang Guowei,Liang Qichao,Wu Mi,Ji Xianlin'
let hallAllOfFameArr = Str.split(',')
console.log(hallAllOfFameArr)
// ["Chen Yinke", "Lu Xun", "Qian Zhongshu", "Hu Shi", "Wang Guowei", "Liang Qichao", "Wu Mi", "Ji Xianlin"]

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, secondSplit){
    var contentStr = this.removeBlankLines(),
        contentStrArr = contentStr.split(firstSplit),
        resultArr = contentStrArr.map((element) => {
            return element.split(secondSplit)
        })
    return resultArr
}
var str = `
Far away is the sound of a tiny bell,Yilin Shadows Ten Thousands of Crows.
Life's Negativity Becomes Today,There is no one in the world against the setting sun.
Breaking mountains and rivers to victory,The rest of the year is bleak.
What year's dream of Songmen Pine Chrysanthemum,He also recognizes other countries as his homeland.
`
console.log(str.strTo2dArr('\n', ','))

In operation, the output results are as follows:

[`The tiny bell sounds far away', `Yilin Ying Wanrao Tibet'. ]
[`A lifetime of negative spirits becomes today', `No one in the world is facing the sunset'. ]
[`Broken mountains and rivers win', `Remaining years send desolate. ]
[`Songmen Pine Chrysanthemum Ho Nian Meng', `and recognize other countries as their homeland'. ]]

Topics: Javascript less ECMAScript REST