Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the string manipulation methods often tested in web front-end interviews?

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the knowledge of "what are the string manipulation methods often tested in web front-end interviews?". In the operation of actual cases, many people will encounter such a dilemma. Next, let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

1. CharAt ()

Returns the character at the specified position.

Var str= "abc" console.log (str.charAt (0)) / / an II, charCodeAt ()

Returns the Unicode encoding of the character at the specified position.

Var str= "abc" console.log (str.charCodeAt (1)) / / 98 III. Concat ()

Connection string.

Var a = "abc"; var b = "def"; var c = a.concat (b); console.log (c); / / abcdefIV, indexOf ()

Retrieve the string. The indexOf () method is case sensitive!

Var str= "Hello world!" console.log (str.indexOf ("Hello")) / / 0console.log (str.indexOf ("World")) / /-1console.log (str.indexOf ("world")) / 6V, match ()

The match () method retrieves the specified value within a string or finds a match of one or more regular expressions. This method is similar to indexOf () and lastIndexOf (), but it returns the specified value instead of the position of the string.

Var str= "1 abc 2 def 3" console.log (str.match (/\ dink Universe)) / / 1236, replace ()

The replace () method is used to replace some characters in a string with other characters, or to replace a substring that matches a regular expression.

Var str= "abc Def!" console.log (str.replace (/ abc/, "CBA")) / / CBA Def! 7. Search ()

The search () method is used to retrieve a substring specified in a string or to retrieve a substring that matches a regular expression. To perform a case-ignored retrieval, append the flag I. If no matching substring is found,-1 is returned.

Var str= "abc DEF!" console.log (str.search (/ DEF/)) / / 48, slice ()

Extract a fragment of the string and return the extracted part in the new string.

StringObject.slice (start,end)

Start: the starting subscript of the fragment to be extracted. If it is a negative number, this parameter specifies the position from the end of the string. That is,-1 refers to the last character of the string,-2 refers to the penultimate character, and so on.

End: the subscript immediately following the end of the clip 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 the parameter is negative, it specifies the position from the end of the string.

Var str= "abc def ghk" console.log (str.slice (6)) / f ghk IX, split ()

Splits a string into an array of strings.

Var str= "abc def ghi jkl" console.log (str.split (")) / / [" abc "," def "," ghi "," jkl "] console.log (str.split (")) / / ["a", "b", "c", "", "d", "e", "f", "", "g", "h", "I", "", "j", "k" "l"] console.log (str.split (", 3)) / / [" abc "," def "," ghi "] X, toLocaleLowerCase ()

Converts a string to lowercase.

Var str= "ABC def!" console.log (str.toLocaleLowerCase ()) / / abc def! ToLocaleUpperCase ()

Converts a string to uppercase.

Var str= "ABC def!" console.log (str.toLocaleUpperCase ()) / / ABC DEF! 12. ToLowerCase ()

Converts a string to lowercase.

Var str= "ABC def!" console.log (str.toLowerCase ()) / / abc def! 13. ToUpperCase ()

Converts a string to uppercase.

Var str= "ABC def!" console.log (str.toUpperCase ()) / / ABC DEF! 14. Substr ()

Extracts a specified number of characters from the string from the starting index number.

StringObject.substr (start,length).

Start: required. The starting subscript of the substring to be extracted. Must be a numeric value. If it is a negative number, 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 penultimate character, and so on.

Length: 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 the stringObject is returned.

Var str= "abc def" console.log (str.substr (2)) / / c defconsole.log (str.substr (2)) / / c de 15, substring ()

Extracts the character between two specified index numbers in a string.

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 the stringObject.

Stop: optional. A non-negative integer that is 1 more positioned in stringObject than the last character of the substring to be extracted. If this parameter is omitted, the substring returned will go all the way to the end of the string.

Var str= "abc def" console.log (str.substring (2)) / c defconsole.log (str.substring (2)) / / c

The same point: if you just write a parameter, both serve the same purpose: both intercept the string fragment from the current subscript to the end of the string.

Substr (startIndex)

Substring (startIndex)

Var str = '123456789 consoleability console.log (str.substr (2)); / / "3456789" console.log (str.substring (2)); / / "3456789"

Difference: second parameter

Substr (startIndex,lenth): the second parameter is to intercept the length of the string (a string of a certain length from the starting point)

Substring (startIndex, endIndex): the second parameter is to intercept the final subscript of the string (intercept the string between two positions, 'with head and no tail').

Console.log ("123456789" .substr (2Power5)); / / "34567" console.log ("123456789" .substring (2p5)); / / methods for manipulating strings added by "123456789" ES6. 1. CodePointAt () let s ='?

The argument to the codePointAt method is the position of the character in the string (starting at 0). In the above code, JavaScript treats "a" as three characters, and the codePointAt method correctly recognizes "a" on the first character, returning its decimal code point 134071 (that is, hexadecimal 20BB7). In the second character (that is, "?" The result of the codePointAt method is the same as the charCodeAt method on the last two bytes of) and the third character "a".

2. String.fromCodePoint ()

ES5 provides a String.fromCharCode method to return the corresponding characters from the code point, but this method does not recognize 32-bit UTF-16 characters (the Unicode number is greater than 0xFFFF).

String.fromCharCode (0x20BB7) / / "subscription"

In the above code, String.fromCharCode cannot recognize code points larger than 0xFFFF, so 0x20BB7 is overflowed, the highest bit 2 is discarded, and finally the character corresponding to code point U+0BB7 is returned instead of the character corresponding to code point U+20BB7.

ES6 provides the String.fromCodePoint method, which can recognize characters larger than 0xFFFF, which makes up for the deficiency of the String.fromCharCode method. In effect, it is just the opposite of codePointAt method.

String.fromCodePoint (0x20BB7) / / "?" String.fromCodePoint (0x78, 0x1f680, 0x79) = ='x\ uD83D\ uDE80y'// true 3. The ergodic interface of the string for offor (let codePoint of 'abc') {console.log (codePoint)} / / "a" / / "b" / / "c"

In addition to traversing strings, the biggest advantage of this traversal is that it can recognize code points larger than 0xFFFF, which cannot be recognized by traditional for loops.

4. At ()

The at method recognizes characters whose Unicode number is greater than 0xFFFF and returns the correct character.

'abc'.at (0) / / "a"' Ji '.at (0) / / "Ji" 5. Normalize ()

Many European languages have intonation and accent symbols. To represent them, Unicode provides two ways. One is to provide accented characters directly, such as u01D1. The other is to provide composite symbols (combining character), that is, the composition of the original character and the accent, the two words match into a single character, such as O (u004F) and "(u030C) composition" (u004Fu030C).

These two representations are visually and semantically equivalent, but JavaScript cannot recognize them.

'\ u01D1FU004F\ u030C' / / false'\ u01D1'.length / / 1'\ u004F\ u030C'.length / / 2

The above code indicates that JavaScript treats composite characters as two characters, resulting in inequality between the two representations.

ES6 provides a normalize () method for string instances, which is used to unify different representations of characters into the same form, which is called Unicode regularization.

'\ u01D1'.normalize () = ='\ u004F\ u030C'.normalize () / / truth 6, includes (), startsWith (), endsWith ()

Traditionally, JavaScript has only the indexOf method, which can be used to determine whether one string is contained in another. ES6 offers three new methods.

* * includes () * *: returns a Boolean value indicating whether the parameter string has been found. * * startsWith () * *: returns a Boolean value indicating whether the parameter string is at the header of the original string. * * endsWith () * *: returns a Boolean value indicating whether the parameter string is at the end of the original string. Let s = 'Hello worldview; s.startsWith (' Hello') / / trues.endsWith ('!') / / trues.includes ('o') / / true

All three methods support the second parameter, which indicates where to start the search.

Let s = 'Hello worldview; s.startsWith (' world', 6) / / trues.endsWith ('Hello', 5) / / trues.includes (' Hello', 6) / / false

The above code indicates that endsWith behaves differently from the other two methods when using the second parameter n. It is for the first n characters, while the other two methods are for the nth position until the end of the string.

7. Repeat ()

The repeat method returns a new string, indicating that the original string is repeated n times.

'x'.repeat (3) / / "xxx"' hello'.repeat (2) / / "hellohello" 'na'.repeat (0) / / "

If the parameter is a decimal, it is rounded.

'na'.repeat (2.9) / / "nana"

If the parameter of repeat is negative or Infinity, an error will be reported.

'na'.repeat (Infinity) / / RangeError'na'.repeat (- 1) / / RangeError8, padStart (), padEnd ()

ES2017 introduces the function of string completion length. If a string is not long enough, it will be completed at the head or tail. PadStart () is used for head completion and padEnd () is used for tail completion.

'x'.padStart (5,' ab') / / 'ababx''x'.padStart (4,' ab') / / 'abax''x'.padEnd (5,' ab') / / 'xabab''x'.padEnd (4,' ab') / / 'xaba'

In the above code, padStart and padEnd accept a total of two parameters, the first parameter to specify the minimum length of the string, and the second parameter to complete the string.

If the length of the original string is equal to or greater than the specified minimum length, the original string is returned.

'xxx'.padStart (2,' ab') / / 'xxx''xxx'.padEnd (2,' ab') / / 'xxx'

If the sum of the length of the string used to complete and the original string exceeds the specified minimum length, the completion string that exceeds the number of digits is truncated.

'abc'.padStart (10,' 0123456789') / / 0123456abc'

If the second parameter is omitted, the space completion length is used by default.

'x'.padStart (4) / / 'x''x'.padEnd (4) / /' x'

A common use of padStart is to specify the number of digits for numeric completion.

'1'.padStart (10,' 0') / / "0000000001" '12'.padStart (10,' 0') / / "0000000012" '123456'.padStart (10,' 0') / / "0000123456"

Another use is the prompt string format.

'12'.padStart (10,' YYYY-MM-DD') / / "YYYY-MM-12"'09-12'.padStart (10, 'YYYY-MM-DD') / / "YYYY-09-12" IX, matchAll ()

The matchAll method returns all matches of a regular expression in the current string.

String template

The template string (template string) is an enhanced version of the string, identified by backquotes (`). It can be used as a normal string, to define a multiline string, or to embed variables in a string. -string template, which is often used in work.

/ / ordinary string `In JavaScript this is not'\ n' is a line- feed.` / / multiline string `In JavaScript this is not leg.`console.log (`string text line 1string text line 2`); / / embedding variables let name = "Bob", time = "today" in the string; `Hello ${name}, how are you ${time}? `

The template strings in the above code are all indicated in backquotes. If you need to use backquotes in the template string, you should escape with a backslash before.

Let greeting = `\ `Yo\ `World!`

If you use a template string to represent a multiline string, all spaces and indents are retained in the output.

$('# list') .html (`first second`)

In the above code, the spaces and newlines of all template strings are preserved, for example, there is a newline before the tag. If you don't want this line break, you can use the trim method to eliminate it.

$('# list') .html (`first second`.trim ())

To embed a variable in the template string, you need to write the variable name in ${}.

Function authorize (user, action) {if (! user.hasPrivilege (action)) {throw new Error (/ / traditionally written as / / 'User' / / + user.name / / +'is not authorized to do'/ / + action / / +'. `User ${user.name} is not authorized to do ${action}. `);}}

You can put any JavaScript expression inside the curly braces, perform operations, and reference object properties.

Let x = 1 y = 2; `${x} + ${y} = ${x + y}` / "1 + 2 = 3" `${x} + ${y * 2} = ${x + y * 2}` / "1 + 4 = 5" let obj = {x: 1, y: 2}; `${obj.x + obj.y}` / "3"

Functions can also be called in the template string.

Function fn () {return "Hello World";} `foo ${fn ()} bar` / / foo Hello World bar

If the value in curly braces is not a string, it will be converted to a string according to the general rules. For example, if there is an object in curly braces, the object's toString method will be called by default.

If the variable in the template string is not declared, an error will be reported.

/ / variable place does not declare let msg = `Hello, ${place} `; / / an error is reported

Because the inside of the curly braces of the template string is to execute the JavaScript code, if the inside of the curly braces is a string, it will be output as is.

`Hello ${'World'} `/ / "Hello World"

Template strings can even be nested.

/ / code from http://caibaojian.com/js-string.html`const tmpl = addrs = > `$ {addrs.map (addr = > `${addr.first} ${addr.last}`). Join (')} `;` "what are the string manipulation methods often tested in web front-end interviews"? thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report