Detailed explanation of the most common and useful string related methods

  • 2021-07-16 01:47:45
  • OfStack

Convert string

You can convert 1 number, Boolean value, or 1 string object:


var myNumber = 24; // 24
var myString = myNumber.toString(); // "24"

var myNumber = 24; // 24
var myString = String(myNumber); // "24"

Split a string into multiple substrings

To distinguish the conversion of a string to an array of substrings, you can use the split () method:


 var myString = "coming,apart,at,the,commas";
 var substringArray = myString.split(","); // ["coming", "apart", "at", "the", "commas"]
 var arrayLimited = myString.split(",", 3); // ["coming", "apart", "at"]

The second parameter in the last line limits the number of items specified by the array parameter.

Gets the length of 1 string

To find the length attribute of how many characters long strings:


 var myString = "You're quite a character.";
 var stringLength = myString.length; // 25

Found 1 substring in string

There are two ways to do this.

Using indexOf ():


 var stringOne = "Johnny Waldo Harrison Waldo";
 var wheresWaldo = stringOne.indexOf("Waldo"); // 7

The indexOf () method searches for the substring from the beginning of the string (through) the first parameter and returns the beginning of the first occurrence of the substring.

Using lastIndexOf ():


 var stringOne = "Johnny Waldo Harrison Waldo";
 var wheresWaldo = stringOne.lastIndexOf("Waldo"); // 22

The lastIndexOf () method is identical, except that it returns the starting position of the last occurrence in the passed substring.

In both methods, if no substring is found, a value of-1 is returned, allowing an optional second parameter to indicate the position in the string of the character you want to start searching for

Replace 1 substring

To replace 1 part or all of a string with a new string, you can use replace ():


 var slugger = "Josh Hamilton";
 var betterSlugger = slugger.replace("h Hamilton", "e Bautista");
 console.log(betterSlugger); // "Jose Bautista"

The first parameter is the substring you want to replace, and the second parameter is the new substring. This will only replace the first instance of the matching substring.

To replace all instances of matching substrings, use the global flags of regular expressions:


 var myString = "She sells automotive shells on the automotive shore";
 var newString = myString.replace(/automotive/g, "sea");
 console.log(newString); // "She sells sea shells on the sea shore"

The second parameter can include a special substitution mode, or it can be a function.

At the given position, find the corresponding character

The character to find is in the specified position, and you can use the charAt () method:


var myString = "Birds of a Feather";
var whatsAtSeven = myString.charAt(7); // "f"

Often, in the case of JavaScript, the first position in the string is referenced as "0" instead of "1".

Alternatively, you can use charCodeAt (), which gives you the character code instead of the character itself:


 var myString = "Birds of a Feather";
 var whatsAtSeven = myString.charCodeAt(7); // "102"
 var whatsAtEleven = myString.charCodeAt(11); // "70"

Note that the character code of bit (11) of the uppercase letter "F" is different from the character code of bit (7) of the lowercase letter "f".

Connecting multiple strings

In most cases, when you concatenate strings, you use the addition operator (+). But you can also choose to use the CONCAT () method:


var myNumber = 24; // 24
var myString = String(myNumber); // "24"
0

You can also append one by one (in the order in which they appear) by appending multiple strings:


var myNumber = 24; // 24
var myString = String(myNumber); // "24"
1

Extract a string (to form a new string)

There are three different ways to create a new string value:

Using the slice () method:


var myNumber = 24; // 24
var myString = String(myNumber); // "24"
2

Using the substring () method:


var stringOne = "abcdefghijklmnopqrstuvwxyz";
var stringTwo = stringOne.substring(5, 10); // "fghij"

For both slice () and substring () methods, the first argument is the starting substring you want, and the second argument (which is optional) is the character-terminated string in the string. So, in the example above, the parameter "5, 10" means the characters 5 through 9 to create a new string.

Use SUBSTR ()


var myNumber = 24; // 24
var myString = String(myNumber); // "24"
4

SUBSTR (), the first parameter represents the character that starts the new string, and the second parameter is optional. But at this time, the second parameter represents the total number of characters that should include the beginning of the character "5" position.

1 string converted to uppercase or lowercase

There are 4 ways to do case conversion. There are two strings converted to all uppercase:


var myNumber = 24; // 24
var myString = String(myNumber); // "24"
5

Converts a string to lowercase:


var myNumber = 24; // 24
var myString = String(myNumber); // "24"
6

Pattern matching

In a string matching pattern, two methods can be used, and their basic working methods are the same.

A string match () method is called and passed through the regular expression:


var myNumber = 24; // 24
var myString = String(myNumber); // "24"
7

exec () method is called with a string:


var myString = "How much wood could a wood chuck chuck";
var myPattern = /.huck/;
var myResult = myPattern.exec(myString); // ["chuck"]
var patternLocation = myResult.index; // 27
var originalString = myResult.input // "How much wood could a wood chuck chuck"

For both methods, only the first match is returned. If no match is found, a null value is returned.

You can also use the search () method, which accepts a regular expression as a 1-only argument and returns the position where the pattern occurs for the first time:


var myNumber = 24; // 24
var myString = String(myNumber); // "24"
9

If no match is found, the method returns "-1".

Compare the sort order of two strings

You can compare two strings to see which 1 letter comes first with localeCompare, and there are three possible return values:


var myString = "chicken";
var myStringTwo = "egg";
var whichCameFirst = myString.localeCompare(myStringTwo); // -1 (except Chrome, which returns -2)
whichCameFirst = myString.localeCompare("chicken"); // 0
whichCameFirst = myString.localeCompare("apple"); // 1 (Chrome returns 2)
stringObject.localeCompare(target)// Formula 

As shown above, if stringObject is less than target, localeCompare () returns a number less than 0. If stringObject is greater than target, the method returns a number greater than 0. If the two strings are equal, or there is no difference according to the local collation, the method returns 0.

if (result) is preferred because the browser can return any negative or positive results before and after < 0) instead of if (result = = =-1), which will not run in the Chrome browser.


Related articles: