Nowadays, all kinds of frameworks and tools “run amok”, everywhere in the principle and source code, more cross-end technology needs us to explore, but if the basic skills are not good, learn what is half the effort, the effect is very bad, take time at the same time to blow confidence. This article, for my plan [light talk front end] series (six), aims to systematically and logically share the knowledge of native JavaScript with you, to help you more easily geographical clear knowledge system, better understanding and memory, I do my best, hope to live up to expectations.

“All information is represented as strings.”

In the previous article, we said that variables make a program a program, so it can also be said that the information transmitted in the virtual world and the real world is represented by strings, so the use and handling of strings is important.

String

Strings, the JavaScript String type, can be defined directly as “” or” “, or can be defined using the String method.

Let STR = "I am a string "; Let str2 = String(" I am also a String ")Copy the code

There are many usage scenarios:

  • File type: When judging whether a file belongs to the file type that we require users to upload, you can check whether it contains the required type string, such as “image” and “video”, after obtaining the MIME value of the file.

  • Input format: When the user is required to input a mobile phone number, or email, check whether the format is correct.

  • Concatenation string: Many times, concatenation is required when the back end of the information presented is not returned as a whole, but rather multiple result combinations.

  • Index: Queries the position of a character in a string, or further determines whether a string begins or ends with a particular character.

  • Interception: Sometimes the data returned by the backend is too long, so it is unnecessary to display all the data, for example, the time. The backend returns a complete “year-month-day hour: minute: second”, and the front-end displays only “year-month-day”.

Wait, we’re going to talk about all of this, but of course, more.

attribute

The common attribute of string is only one — length, which is used to detect the length of characters. For example, we often limit the length of user input “name, description”. One is for general consideration, and the other is that the content is too long, which will affect the page display, so we can detect the length of input string and give hints. (You don’t need to do this now, native or component libraries will support it)

methods

For character

The first method: charAt()

The argument is the index bit of the character.

let str = "hello world";
str.charAt(4)   //"o"
Copy the code

Second method: brackets

Again, using an index

let str = "hello world";
str[4]   //"o"
Copy the code

String comparison

We’ve already mentioned string comparisons when we talked about numbers, because numbers are a type of character, and when they appear as strings, they follow string rules.

Of course, the operators are the same, except that their ASCII codes are compared.

'a' > 'b'  //false
'11' > '2' //false
'a' > 'A'  //true
Copy the code

The third expression ‘a’ >’ a ‘is valid. However, it is not surprising that each character has its own ASCII code value, depending on the size of the value, even the case of the same letter, so that in some cases that are case-insensitive, you can use the following method to convert first and then compare.

Case conversion

toLowerCase()/toUpperCase()

You can see from the method name that Lower is converted to lowercase and Upper to uppercase.

let str = "heLLo World";
str.toLowerCase();  //"hello world"
str.toUpperCase();  //"HELLO WORLD"
Copy the code

But then you might ask, how do I know if it’s a letter, so I just roll it? Is there any way to tell if the letters don’t turn around?

Check code

The ASCII range of a character string can be used to compare the ASCII range of a character string.

charCodeAt()

The ASCII range of A-Z is “65-90”, and the ASCII range of A-Z is “97-122”.

Well, just compare them with the character codes you typed.

let str = "h".charCodeAt();
(str >= 65 && str <= 90) || (str >= 97 && str <= 122)  //true
Copy the code

Since letters can be judged, is our mother tongue Chinese feasible? Of course.

Both letters and Chinese characters have ranges, and the encoding of Chinese characters is greater than 255. You only need to check whether any character in the string is greater than 255.

Let STR = "STR ". CharCodeAt (); str > 255 //trueCopy the code

Similarly, numbers can be used, and I won’t repeat them here.

Well, it says how to check if it is “letter, text”, but if the user typed nothing, click a few Spaces? Usually, the blank space is not meaningful, do not need to input, there is a way to know, know how to do?

If there is a

indexOf()/includes()

These two methods can be used when we need to detect whether a particular character is contained in a string.

IndexOf () returns the character index, and includes() returns a Boolean value. So let’s just check for Spaces.

let str = "hello world"; str.indexOf(' '); //5 str.includes(' '); //true // Detect nonexistent character str.indexof ('p'); //-1 str.includes('p'); //falseCopy the code

If a character does not exist, it returns -1. If a character does not exist, it returns true/false.

IndexOf() also has a sibling method, lastIndexOf(), which returns the indexOf the last occurrence of a character in a string.

let str = "hello world w abc w"; str.indexOf('w'); //6 str.lastIndexOf('w'); / / 18Copy the code

So, apart from the first and the last, can we trace the ones in between? It is also possible to add one more parameter:

indexOf(searchValue [, fromIndex])

str.indexOf('w',7); //12 str.lastIndexOf('w',7); / / 6Copy the code

Similarly, the includes() method can have a starting query location, but it is not usually used.

Looking at these methods, do you think of detecting file types mentioned above? Usually, the MIME type of a file is image/ PNG. You only need to detect image to determine the image type.

Ok, so this method tells us if we have Spaces, and then what do we do?

replace

Strings give us the ability to replace the original string with an existing string.

replace(regexp|substr, newSubStr|function)

The first argument can be a string or a regular expression, and the second argument can be a new string or a function.

We’re just going to use strings here. If you don’t need a space, just replace it with “”.

let str = "hello world";
str.replace(' ','');  //"helloworld"
Copy the code

This feels similar to the global substitution we use in the editor or word, but with JavaScript code, sometimes it’s useful, you don’t need to find a character somewhere to change, you can just replace it.

However, removing whitespace is just one of the cases that Replace can handle, and there are ways to specifically remove whitespace.

Remove the blank space

trim()/trimStart()/trimEnd()

The string itself has several methods for removing whitespace. Trim () is often used to remove Spaces from user input data.

Such as:

let str = "  hello world  ";
str.trim();  //"hello world"
Copy the code

As you can see, the whitespace is removed from both sides of the string, but not from the middle.

This method is not supported in some older browsers, so you can fall back to the replace() method above for compatibility.

The other two Start and End remove whitespace from “left” or “right”, respectively.

Now, to improve the rationality of user input data, trim-correlation preprocessing is almost standard.

Given the concept of “left” and “right”, is there a way to determine if the leftmost or rightmost character in a string is a particular character? Must be.

What character does it begin/end with

startsWith(searchString[, position]) str.endsWith(searchString[, length])

The beginning and the end of each sentence are the same.

Let STR = "shenzhen aaa.png"; STR. StartsWith (" shenzhen "); //true str.endsWith(".png"); //trueCopy the code

The two methods have two second arguments that represent different meanings. The first argument can give the position of the initial query, and the last argument can give a length. You can check whether the specified length of the string ends in a string.

Does it feel like we can use this method when we look at file types? Theoretically possible, but with two drawbacks:

  • A lot of images have file paths that don’t end with file types, so you might add a timestamp or something like that, so it doesn’t work.
  • There are many extensions for each file type, and if the requirements are very loose, there are many mappings to be written and changes to be made, resulting in poor robustness and maintenance.

So it is better to choose a more suitable method according to the specific scenario.

Head/tail filling

Now that you have the ability to query heads and tails, you should also have the ability to add heads and tails.

padStart()/padEnd()

Fills the specified string at the beginning or end of the current string until the specified length is reached.

So what are the possible use scenarios, you can look at it in terms of characteristics, not specifying string, specifying length, when do you need to specify length?

When there are fixed digits — phone number, ID number, zip code, etc.

When we need to make some bits invisible by filling in “”, we can crop the string first, and then fill in enough” “at the beginning or end of one of the strings to reach the number of digits needed, and then concatenate it.

There is another way to do the same thing — repeat().

You can repeat the specified string a certain number of times, that is, after the above string is intercepted, the number of digits to be filled is obtained, and then splice the repeat after processing, or.

Here is a brief description of the possible scenarios, which may be rarely used in practice, or there may be a better method and a more suitable scenario.

Well, I’ve sneaked in two new methods — clipping and splicing.

String clipping

This is one of the most important and commonly used methods.

It has several species:

  • Slice () — Intercepts the location interval.
  • Substr () — intercepts the specified amount.
  • Substring () – Returns the characters between the specified subscripts.

The slice() method accepts one required and one optional argument. See the sample:

let str = "hello world"; str.slice(5); / / "world" STR. Slice (5, 7); //" w"Copy the code

If only one parameter is passed, the position of the parameter is cut to the end of the part. If two parameters are passed, it is the part between the two parameter positions. It is worth noting that it supports passing negative values.

str.slice(-6)  // " world"
Copy the code

It’s the same as if you were passing a 5, or you could say, if you’re passing a positive, you’re going to start at the front, and if you’re passing a negative, you’re going to start at the end, and you’re going to truncate the difference. Of course, you have to have both the positive and the negative. For example, (3,5), (-6,-2), the front section is 2, and the reverse section is 4.

The substr() method intercepts a specified number of characters from a specified position.

let str = "hello world"; str.substr(5); / / "world" STR. Substr (5, 2); //" w"Copy the code

As you can see, this is the same as the slice() method without a bit argument, but with a bit argument, it is different.

It also differs from Slice in that it can be different because it is a specified number of digits.

STR. Substr (- 2, 2); // "ld"Copy the code

The substring() method appears to be doing the same thing as the slice() method. What’s the difference?

  • Intercept algorithm
let str = "hello world"; STR. Slice (5, 2); / / "" STR. The substring (5, 2); //" w"Copy the code

It can be seen that the slice method has a calculation order. When the position parameter is positive, no results will be obtained from back to front. Similarly, when the position parameter is negative, no results will be obtained from front to back.

Substring, on the other hand, returns only the characters between two subscripts, regardless of the order of interception.

  • Location algorithm
let str = "hello world"; STR. Slice (- 2, 3); / / "" STR. Slice (3, 20); / / "lo world" STR. The substring (- 2, 3); / / "hel" STR. The substring (3, 20); //"lo world"Copy the code

As you can see, slice counts forward from the end when the position is negative, thus failing to get the result, and subString does not count backwards, but returns the string as if it were starting from scratch. The result is the same when the number of bits exceeds the length of the string.

As discussed above, string manipulation has a similar effect to some extent and will not be used all day, just choose a more suitable one if necessary.

String splicing

Finally, string concatenation, one of the most common requirements.

The first thing that comes to mind is the “+” operator, which has already been mentioned and is the most convenient to add as many as you can, but strings have their own concatenation method, concat().

let str = "hello";
str.concat('lily','and','lucy');  //"hellolilyandlucy"
Copy the code

Nevertheless, the + operator is recommended most of the time.

However, when you are using long strings and you need to concatenate variables, it is better to use another method — template strings.

Template strings are a new addition to ES6. We used to write:

let name = 'Tom'; let age = 10; Let intro = "my name is + name + ',' + age + ';Copy the code

Template strings enclose strings in backquotes and can parse variables.

Let intro = 'my name is ${name}, I am ${age} years old';Copy the code

There are several advantages compared with before:

  • More concise writing, do not need to pay special attention to the use of plus signs and quotation marks, low error probability.
  • Whitespace and indentation remain in the output, and previous methods required concatenation of corresponding characters.
  • You can evaluate using JavaScript expressions in {}, such as {a/b}.

Convert to an array

split([separator[, limit]])

This is another common way to use string manipulation, why? Because a lot of times, the data that we put on the page, or get from the back end, is going to be a string.

Like “1,3,5,6,7” or “zhang SAN, li si, wang wu”

If it’s just text, it’s not a problem, but if you need to do other things like sort, filter, list rendering, etc., strings are not powerful enough, and it’s easy to turn them into arrays and use array-related capabilities.

Let numStr = '1,3,5,6,7'; numStr.split(','); // ["1", "3", "5", "6", "7"] let numStr = '1-3-5-6-7'; numStr.split('-'); // ["1", "3", "5", "6", "7"]Copy the code

This method also has a second, less commonly used, parameter limit, which specifies the limit of the delimiter.

numStr.split(',',3); (3) [" 1 ", "3", "5"]Copy the code

Stringing of objects

When we talked about operators and types, we said that an object can also be converted to a string. What is the method? The toString? valueOf?

Take a look:

let obj = {
    a:'b'
}
obj.toString()  //"[object Object]"
obj.valueOf()  //{a:'b'}
Copy the code

It looks like toString won’t do it, valueOf does, but

typeof obj.valueOf()  //"object"
Copy the code

It’s not a string, it’s still an object, so how do you actually convert an object to a string?

JSON.stringify()

JSON.stringify(obj)  //"{"a":"b"}"
Copy the code

This will actually convert to a string.

Otherwise, arrays are similar.

This often happens when an object needs to be deeply copied or converted into a JSON string when a request is sent to the back end.

Regular match

replace()/match()/search()

I’ve covered a lot of string look-and-replace and clipping, but at some point, simple operations, or fixed values, don’t satisfy complex conditions, and you need another important weapon — regex.

A regular expression is a character rule. A small number of writing rules can be used to match a large class of character combinations to solve problems more efficiently.

The replace () example:

The replace() method has been used above, simply replacing one string with another, but it can also match the replacement with a re to achieve more power.

var reg = /apples/gi;
var str = "Apples are round, and apples are juicy.";
var newstr = str.replace(reg, "oranges");   // oranges are round, and oranges are juicy.
Copy the code

This code replaces “apples” with “oranges” globally, case insensitive. Here is just a simple example, more powerful effect, need to use more regular matching techniques, no expansion.

Match () example:

let str = "123Abc";
let reg = /[A-Z]/g;
str.match(reg);  //["A"]
Copy the code

The match() method returns an array that matches the regular expression. This is much more convenient than checking the character type and then printing the character at the specified position.

Search () example:

var str = "123AbB";
var reg = /[A-Z]/g;
str.search(reg)  //3
Copy the code

The search() method returns the indexOf the first character that meets the criteria. Functionally, it is similar to indexOf(), but matches with rules that cover a larger range and are suitable for examining certain types of characters.

conclusion

This brings the discussion of “strings” to a close.

The “string” world is just as rich and even more complex than the “number game,” which shows how important strings are in programming and how many different scenarios they can be used in, which is probably why developers are preparing more tools for them.

Content is slightly more, can slowly digest, and in the process of continuous use gradually skilled bar ~

See you next!

Blog link:

【 Talk about front-end 】 “string” jianghu

Series of articles:

【 Talk about the front end 】 good basic skills, easy to learn with me

Small role, big use — variable

Why is everything an object?

[Talking about the front end] Those “unreasonable value” operations

Digital games in JavaScript