JavaScript ultimate interview question string: Is "105" greater than "44"? How much is "123b" converted to Number? Can negative numbers be passed to slice, substring, substr, etc.

Preface

String is one of the basic variables in JavaScript, and it also has special properties. Its variables cannot be changed . There are two ways to create objects: non-object, for example var x = "Bill"; object, for example var y = new String("Bill"). When a string is created using a non-object method, a pointer is stored on the stack pointing to a constant in the String pool; when a string is created using an object method, a pointer is stored on the stack pointing to a String object in the heap.
Note: Do not frequently perform operations such as additions, deletions, and substitutions on a string variable, because String is an immutable variable, and operations such as additions, deletions, and substitutions are essentially the creation and destruction of multiple objects. Frequent operations affect performance.

1. Comparison of strings

1.Equality comparison

var x = "Bill";             
var y = new String("Bill");
var z = "Bill";
x == y // true
x === y // false
x === z // true

Non-object strings compare the values ​​in the String constant pool, while object strings compare pointer addresses.
In addition, when creating string variables, please do not use newto create, it will slow down the execution speed.

2. Size comparison

The comparison between strings is to first take the ASCII codes of the strings in sequence, and then determine which ASCII code is larger first. To convert characters to ascii code: use charCodeAt(); to convert characters to ascii code: use fromCharCode();

"105" > "44" // false
"1" > "0987" // true
"1.00004a" > "1.00004b" // false
"absffz" > "absffA" // true

The comparison starts from the ASCII code of the first character. If the comparison cannot be determined, the second character is compared, and so on.
大写字母A 到Z 的值是从65 到90,小写a到z 是从91 到 122.
The specific code stamp of each character☞here .
Comparison between strings and numbers can☞refer to this article

Example: When the date type formats are the same, you can directly compare the size of the string format to determine the size of the date, for example: "2020-05-01" > "2020-04-02"

2. Convert String to Number

Five methods are provided: Number(), parseInt(), parseFloat(), new Number(), * | / 1 It is
recommended to use * | / 1automatic implicit conversion to digital format, which is the most efficient. It is not recommended to use new Number() object creation method, the least efficient

var a = "123.01"
var b = "123.01abc"
var c = "a123.01bc"
var d = "abc123"
Number(a) // 123.01
Number(b) // NaN 
Number(c) // NaN
Number(d) // NaN
parseInt(a) // 123
parseInt(b) // 123
parseInt(c) // NaN
parseInt(d) // NaN
parseFloat(a) // 123.01
parseFloat(a) // 123.01
parseFloat(a) // NaN
parseFloat(a)// NaN

Number(" 123 ") // 123
parseInt(" 123 ") // 123
parseFloat(" 123  ") // 123
// * | /
a*1 , a/1 // 和Number结果一致

Summary: Number will convert characters with non-empty and non-numeric characters into NaN. parseInt and parseFloat will parse characters that are non-empty and non-numeric and convert them into NaN at one time. The difference is that they will intercept the value of the previous number. * | / 1 has the same result as Number.

3. Add and subtract strings

1.Add

"ab" + "b" // abb
"ab" + "cd" // abcd

2. Subtraction

"ab" - "b" // NaN
"ab" - "cd" // NaN
"123" - "12" // 111

Addition and subtraction with non-strings can ☞Refer to this article

4. Common operation scenarios such as string interception and replacement

1. Scene 1, interception

(1) slice

Syntax: stringObject.slice(start,end)
start The starting index of the slice to be extracted. If it is a negative number, this parameter specifies the position starting from the end of the string. That is, -1 refers to the last character of the string, -2 refers to the second to last character, and so on. end The index
immediately following the end of the segment to be extracted . If this parameter is not specified, the substring to be extracted includes the string from start to the end of the original string. If this parameter is negative, it specifies the position from the end of the string.

// 正数
"abcd".slice(0) //"abcd"
"abcd".slice() //"abcd"
"abcd".slice(1,5) //"bcd"
"abcd".slice(5,1) //""
// 负数时从右向左数数
//start=-1从d开始,最后一位,end接受正数大于0,或者不传,其他为空
"abcd".slice(-1) // "d"
"abcd".slice(-1,1) //"d"
"abcd".slice(-1,2) //"d"
"abcd".slice(-1,-1) // "" 
"abcd".slice(-1,-2) // ""
//start=-3从b开始,end接受负数>=-2正数大于1,其他为空
"abcd".slice(-3,-2) // "b"
"abcd".slice(-3,-1) // "bc"
"abcd".slice(-3,2) // "b"
"abcd".slice(-3,3) // "bc"
//start=1从b开始,end接受负数>=-2正数大于1,其他为空(和上面的例子原理一样)
"abcd".slice(1,-2) // "b"
"abcd".slice(1,-1) // "bc"
"abcd".slice(1,2) // "b"
"abcd".slice(1,3) // "bc"

Description:
The slice() method can extract a certain part of a string and return the extracted part as a new string.
The String object methods slice(), substring(), and substr() (deprecated) all return a specified portion of a string. slice() is more flexible than substring() because it allows negative numbers as arguments. slice() differs from substr() in that it uses two character positions to specify a substring, whereas substr() uses character positions and length to specify a substring.
Also note that String.slice() is similar to Array.slice().

(2)substring

Syntax: stringObject.substring(start,stop)
start Required. A non-negative integer that specifies the position of the first character of the substring to be extracted in stringObject. It is found that negative numbers are equivalent to passing 0 , which is meaningless.
stop
is optional. A non-negative integer that is 1 more than the last character of the substring to be extracted in stringObject.
If this parameter is omitted, the returned substring will go to the end of the string. It is found that negative numbers are equivalent to passing 0 , which is meaningless.

// 正数
"abcd".substring(0) //"abcd"
"abcd".substring() //"abcd"
"abcd".substring(1,5) //"bcd"
"abcd".substring(1,2) // "b"
"abcd".substring(5,1) //"bcd"
"abcd".substring(4,2) //"cd"
// 传负数时不报错,但结果非臆想的,相当于0
"abcd".substring(-1) //"abcd"
"abcd".substring(-1,5) //"abcd"
"abcd".substring(1,-5) // "a"
"abcd".substring(1,0) //"a"
"abcd".substring(-1,-5) // ""
"abcd".substring(0,0) // ""

(3)substr

Syntax: stringObject.substr(start,length)
start Required. The starting index of the substring to be extracted. Must be a numeric value. If negative, this parameter declares the position from the end of the string. That is, -1 refers to the last character in the string, -2 refers to the second to last character, and so on.
length is optional. The number of characters in the substring. Must be a numeric value. If this parameter is omitted, the string from the beginning to the end of stringObject is returned. Returns an empty string if it is a negative number

// 正数
"abcd".substr(0) //"abcd"
"abcd".substr() //"abcd"
"abcd".substr(1,5) //"bcd"
// 负数
"abcd".substr(-1) //"d"
"abcd".substr(-1,5) //"d"
"abcd".substr(-2,1) // "c"
"abcd".substr(-2,-1) // ""
"abcd".substr(2,-1) // ""

Note:
The parameters of substr() specify the starting position and length of the substring, so it can be used instead of substring() and slice(). start can be a negative number meaningfully.
Important: ECMAscript does not standardize this method and therefore discourages its use.
Important: In IE 4, the value of parameter start is invalid. In this BUG, ​​start specifies the position of the 0th character. In later versions, this BUG has been corrected.

Summary (I understand clearly after reading it):

1.slice第一个参数和第二个参数都是字符串的索引值,都可为负数,代表反向的;其返回的子字符串必须是从左到有的,即第二个参数的索引不可以在第一个索引的前面,否则为空
2.substring第一个参数和第二个参数都是字符串的索引值,但是负数特殊相当于0,不代表反向的索引;比slice而言第二个索引可以在第一个索引前面 3.substr ECMAscript标准化没有标准化,不建议用;第一个参数为字符串的索引值,可以为负数,代表反向的索引,第二个参数为截取字符串的长度,因此为负数时相当于0,返回空字符串

2. Scenario 2. Replacement

replace syntax: stringObject.replace(regexp/substr,replacement)
regexp/substr
is required. A RegExp object that specifies the substring or pattern to be replaced.
Note that if the value is a string, it is retrieved as a literal text pattern, rather than first being converted to a RegExp object.
replacement required. A string value. Specifies functions for replacing text or generating replacement text.

// 将把 "Doe, John" 转换为 "John Doe" 的形式
let name = "Doe, John";
name.replace(/(\w+)\s*, \s*(\w+)/, "$2 $1");
// 将把所有的花引号替换为直引号:
name = '"a", "b"';
name.replace(/"([^"]*)"/g, "'$1'");
// 把字符串中所有单词的首字母都转换为大写:
name = 'aaa bbb ccc';
uw=name.replace(/\b\w+\b/g, function(word){
    
    
  return word.substring(0,1).toUpperCase()+word.substring(1);}
  );

Case: Convert string to camel case

var str="border-bottom-color";
function convertToCamelCase(str) {
    
    
 return str.replace(/-(\w)/g, function($0, $1) {
    
    
    return $1.toUpperCase();
  });
};
convertToCamelCase(str);

Note:
replacement can be a string or a function. If it is a string, then each match will be replaced by the string. But the $ character in replacement has a specific meaning. As shown in the following table, it illustrates that the string obtained from the pattern match will be used for replacement.

character replacement text
$1、$2、…、$99 Text that matches subexpressions 1 through 99 in regexp.
$& Substring matching regexp.
$` The text to the left of the matched substring.
$’ The text to the right of the matched substring.
$$ Direct quantity symbol.

3. Scenario 3, object and string conversion

var obj={
    
    "a":"dt","b":"yuiyi"}
var obj1={
    
    "a":"dt","b":{
    
    "a":"dt"}}
var str = JSON.stringify(obj) // '{"a":"dt","b":"yuiyi"}'
var str1 = JSON.stringify(obj1) //'{"a":"dt","b":{"a":"dt"}}'
JSON.parse(str) // {a: "dt", b: "yuiyi"}
JSON.parse(str1) //{a: "dt", b: {…}}

It can be used for shallow copying of objects and serialized parameter passing of objects, such as routing query parameters in Vue.

4. Scenario 4, string regularization

Strings support 4 regular methods

api describe
match() Finds a match for one or more regular expressions.
replace() Replaces a substring matching a regular expression.
search() Retrieve values ​​that match a regular expression.
split() Split string into string array

For specific usage, please refer to w3school

5. Scenario 5. Translation

  1. Don't escape characters in a string unnecessarily, why? Backslashes impair readability, so they should only appear when necessary.
// bad
const foo = '\'this\' \i\s \"quoted\"';

// good
const foo = '\'this\' is "quoted"';
const foo = `my name is '${
      
      name}'`;
  1. In regular expressions and special character uses such as \nline feed, \ttab, etc., escaping must be added.
code result
\b backspace key
\f Page change
\n new bank
\r Enter
\t horizontal tab
\v vertical tab
// 包含千分位的数字校验
let reg = /^\d{1,3}(,\d{3})*(\.\d{1,2})?$/
// 包含斜杆或者反斜杆校验
let reg1 = /\/|\\/
reg1.test("\\") // true

References:
https://github.com/airbnb/javascript#strings
https://www.w3school.com.cn/js/js_strings.asp
http://c.biancheng.net/c/ascii/

Guess you like

Origin blog.csdn.net/qq_29510269/article/details/106409476