20 common methods of (JavaScript native) string + string traverser + template string

Keywords: Javascript Java encoding

Reprinted from:
https://blog.csdn.net/qq_39872652/article/details/81517626

20 common methods of (JavaScript native) string + string traverser + template string

It's a common saying that no matter a professional or a fledgling Xiaobai believes that he is familiar with JavaScript strings, and the frequency and importance of string element in the whole development process of the front end It's incomparable. Today we're going to uncover the mystery of strings under JavaScript, hoping to really make it simple.

##In JavaScript, the String type is the basic data type, which is different from the reference type in other background languages such as Java.

##Definition string:

let str = "Study hard,Make progress every day";

1, 19 common methods of string:

> -1).Find the index of the location of the specified character

 ①.indexOf("Specify character ");Front to back

  1. // A.indexOf(Xxx)
  2. console.log(str.indexOf("learn"));// Print 2
  3. console.log(str);// Study hard in printing and make progress day by day
/**
 * -1).Use: find the index of the specified character from the front to the back
 * -2).Usage: str.indexOf("specified character");
 * -3).Return value: if found - > return the index where the specified character is located
 *           If not found - > Return - 1
 * -4).Change original string: no
 */

 ②.lastIndexOf("Specify character ");Back to front

  1. // B.lastIndexOf(Xxx); looking forward from the back
  2. console.log(str.lastIndexOf("Xi"));// Print 3
  3. console.log(str);// Study hard in printing and make progress day by day
/**
 * -1).Use: find the index of the location of the specified character from the back to the front
 * -2).Usage: str.lastIndexOf("specified character");
 * -3).Return value: if found - > return the index where the specified character is located
 *           If not found - > Return - 1
 * -4).Change original string: no
 */

 ③.search("Specify character "/regular expression ); -> regular expression

  1. // C.search(Xxx); regular expression support
  2. console.log(str.search(","));// Print 4
  3. console.log(str.search(/[\u4e00-\u9fa5]$/));// Print 8
  4. console.log(str);// Study hard in printing and make progress day by day
/**
 * -1).Use: find the index where the specified character is located
 * -2).Usage: str.search (specified character / regular expression);
 * -3).Return value: if found - > return the index where the specified character is located
 *           If not found - > Return - 1
 * -4).Change original string: no
 */

> -2).Find the characters corresponding to the specified index

 ①.charAt(Indexes);

  1. // A.charAt(Xxx);
  2. console.log(str.charAt(0));// Print well
/**
 * -1).Usage: find the corresponding string by specifying the index
 * -2).Usage: str.charAt (specify index);
 * -3).Return value: if found - > return corresponding character
 *           If not found - > return "" - > empty string
 * -4).Change original string: no
 */

 ②.charCodeAt(Indexes);

  1. // B.charCodeAt(Xxx);
  2. console.log(str.charCodeAt(0));// Print 22909
  3. console.log(str)// Study hard in printing and make progress day by day
/**
 * -1).Usage: find the Unicode code corresponding to the corresponding string by specifying the index
 * -2).Usage: str.charcodeat (specify index);
 * -3).Return value: if you find - > return the Unicode encoding of the character in the specified location
 *           If not found - > return NaN
 * -4).Change original string: no
 */

 ③.match("Character "/regular expression ); -> regular expression

  1. console.log(str.match("day"));// Print ['Day', index: 5, input: 'study hard and make progress day by day']
  2. console.log(Object.prototype.toString.call(str.match("day")));// Print [object Array]
  3. console.log(str.match(/[good]/g));// Print ['good', 'good']
  4. console.log(str);// Study hard in printing and make progress day by day
/**
 * -1).Usage: find corresponding characters by specifying characters, support regular expression
 * -2).Usage: str.match("character" / regular expression);
 * -3).Return value: if found - > return an array storing the specified characters
 *           If not found - > return null
 * -4).Change original string: no
 */

> -3).String truncation

 ①.substr(Initial index, Interception number);

  1. // A.substr(num1, num2);
  2. console.log(str.substr(0, 2));// Print well
  3. console.log(str);// Study hard in printing and make progress day by day
/**
 * -1).Use: intercept string
 * -2).Usage: str.substr (starting index, number of interceptions);
 * -3).Return value: returns a truncated new string
 * -4).Change original string: no
 */

##Expand - > implement string cloning based on substr method

console.log(str.substr(0, str.length));// Study hard in printing and make progress day by day

 ②.substring(Initial index, End index);Left and right open

  1. // B. Substring (start index, end index); left closed right open
  2. console.log(str.substring(0, 4));// Print and learn
  3. console.log(str);// Study hard in printing and make progress day by day
/**
 * -1).Use: intercept string
 * -2).Usage: str.substring (start index, end index);
 * -3).Return value: returns a truncated new string
 * -4).Change original string: no
 */

##Extension - > string cloning based on substring method

  1. // Extension - > string cloning based on substring method
  2. console.log(str.substring(0, str.length));// Study hard in printing and make progress day by day

 ③.slice(Initial index, End index);Left and right open,Negative index supported

  1. // C. Slice (start index, end index);
  2. console.log(str.slice(0, 4));// Print and learn
  3. console.log(str.slice(0, -1));// Study hard in printing and learn from
/**
 * Calculation method of negative index: 9 + - 1
 * str.slice(0, -1) => str.slice(0, str.length + -1)
 */
/**
 * -1).Usage: intercept string, support negative index
 * -2).Usage: str.slice (start index, end index);
 * -3).Return value: returns a truncated new string
 * -4).Change original string: no
 */

##Extension - > string cloning based on slice method

console.log(str.slice(0, str.length));// Study hard in printing and make progress day by day

 

> -4).String split, replace

 ①.split:split("Separator ");

  1. // A.split("separator");
  2. console.log(str.split(","));// Print ['study hard', 'day up']
  3. console.log(str);// Study hard in printing and make progress day by day
/**
 * -1).Use: split string
 * -2).Usage: str.split("separator");
 * -3).Return value: returns an array of strings completed by segmentation
 * -4).Change original string: no
 */

 ②.replace:replace("Replaced character ", "Replace character ");

  1. let strr = str.slice(0, str.length);
  2. console.log(strr.replace("Well", "earnest"));// Print, study hard and make progress day by day
  3. console.log(strr);// Study hard in printing and make progress day by day
/**
 * -1).Use: replace the specified character
 * -2).Usage: str.replace("old string", "new string");
 * -3).Return value: returns the replacement completed string
 * -4).Change original string: no
 */

> -5).Case conversion of characters

 ①.Lowercase to uppercase:toUpperCase();

  1. // A.toUpperCase
  2. strr = "Hello World";
  3. console.log(strr.toUpperCase());// Print HELLO WORLD
  4. console.log(strr);// Print Hello World

 ②.Capitalize to lowercase:toLowerCase();

  1. strr = strr.toUpperCase();
  2. console.log(strr);// Print HELLO WORLD
  3. console.log(strr.toLowerCase());// Print hello world

> -6).Find the specified character

 ①.includes("Specify character ");Find in entire string

  1. // A.includes("specified character");
  2. console.log(str.includes("day"));// Print true
  3. console.log(str);// Study hard in printing and make progress day by day
/**
 * -1).Use: find the specified character
 * -2).Usage: str.includes("specified character");
 * -3).Return value: if found - > return true
 *           If not found - > return false
 * -4).Change original string: no
 */

 ②.startsWith("Specify character ");Just at the beginning

  1. // B.startsWith("specified character");
  2. console.log(str.startsWith("good"));// Print true
  3. console.log(str);// Study hard in printing and make progress day by day
/**
 * -1).Use: find the specified character (only find the beginning of the string)
 * -2).Usage: str.startsWith("specified character");
 * -3).Return value: if found - > return true
 *           If not found - > return false
 * -4).Change original string: no
 */

 ③.endsWith("Specify character ");Just at the end

  1. // C. Endswith (specified character);
  2. console.log(str.endsWith("upper"));// Print true
  3. console.log(str);// Study hard in printing and make progress day by day
/**
 * -1).Use: find the specified character (only find the end of the string)
 * -2).Usage: str.endsWith("specified character");
 * -3).Return value: if found - > return true
 *           If not found - > return false
 * -4).Change original string: no
 */

> -7).Duplicate string

 ①.repeat(Xxx);

/**
 * Be careful:
 *  -1).If the parameter is decimal, round down.
 *  -2).If the parameter is a non significant number (non numeric string / NaN), the number of repetitions is calculated as 0.
 *  -3).If the parameter is a numeric string / Boolean, the advanced row data type is converted to Number and the Number of repetitions is calculated.
 */
  1. console.log(str.repeat(2.6));// Study hard in printing, study hard every day, study hard every day
  2. console.log(str);// Study hard in printing and make progress day by day
  3. console.log(str.repeat("Ha"));// Print empty
  4. console.log(str.repeat(NaN));// Print empty
  5. console.log(str.repeat("2"));// Study hard in printing, study hard every day, study hard every day
  6. console.log(str.repeat(true));// Study hard in printing and make progress day by day
/**
 * -1).Use: duplicate string
 * -2).Usage: str.repeat(Xxx);
 * -3).Return value: a string that repeats a specified number of times
 * -4).Change original string: no
 */

> -8).String completion

 ①.padStart(Specify string length, Fill element);Fill in at the beginning

  1. // A. Padstart (specify the length of the string and replace the characters);
  2. console.log(str.padStart(11, "ab"));// Print ab to study hard and make progress day by day
  3. console.log(str);// Study hard in printing and make progress day by day
/**
 * -1).Use: string completion (from scratch)
 * -2).Usage: str.padstart (specify the length of string, replace character);
 * -3).Return value: string after completion
 * -4).Change original string: no
 */

 ②.padEnd(Specify string length, Fill element);Fill at the end

  1. // B. Padend (specify the length of string, replace character);
  2. console.log(str.padEnd(11, "ab"));// Print and study hard, ab
  3. console.log(str);// Study hard in printing and make progress day by day
/**
 * -1).Use: string completion (from the end)
 * -2).Usage: str.padstart (specify the length of string, replace character);
 * -3).Return value: string after completion
 * -4).Change original string: no
 */

> -9).Remove leading and trailing spaces from string

 ①.trim();Remove leading and trailing spaces

  1. let str_4 = " study hard ";
  2. console.log(str_4.trim());//study hard
  3. console.log(str_4);// study hard
/**
 * -1).Use: String space removal
 * -2).Usage: str.trim();
 * -3).Return value: returns a new string without leading and trailing spaces
 * -4).Change original string: no
 */

2, String traverser

for ... of ...

  1. for(let item of str) {
  2. console.log(item);
  3. /**
  4. * day
  5. * day
  6. * towards
  7. * upper
  8. */
  9. }

3, Template string

Defining variables

let price = 100;
Remember us ES5 Including the previous string splicing is a time-consuming and unpleasant operation...A plus sign,It's hard to read
  1. let str_1 = "Apple price:" + price + "element";
  2. console.log(str_1);// Print apple price: 100 yuan

ES6 Template string for:Solved this problem

##How to use the template string: wrap it with "(" the key above the tab key ") and reference variables with ${Xxx}.

  1. // The template string of ES6 is wrapped by '` (` ` the key above the tab key), and variables are referenced by ${Xxx}.
  2. str_1 = `Apple price:${price}element`;
  3. console.log(str_1);// Print apple price: 100 yuan

So not only does it not have to be a plus sign,And it's more intuitive,Another advantage of template strings is that they retain formatting:

ES5

  1. let str_2 = "1" +
  2. "2";
  3. console.log(str_2);// Print 12

ES6 The template string of will keep our typing'Enter'Later formats

  1. let str_3 = `1
  2. 2`;
  3. console.log(str_3);

Print results:↓↓↓

summary:This chapter mainly introduces 20 common methods of string and ES6 Provided string traverser and template string. Basically, this blog post covers the vast majority of string operations in our daily development. I hope to share with you!!!Please leave a message below if you have any comments or suggestions,I will reply in the first time!!!

 

 

            </div>

Posted by latinofever on Tue, 31 Dec 2019 19:56:02 -0800