JavaScript - String of data type

Posted by bobocheez on Tue, 25 Jan 2022 11:54:38 +0100

A data type is a literal type

There are eight basic data types in JavaScript (the first seven are basic data types, also known as primitive types, while object is a complex data type).

  • Number is used for any type of number: integer or floating-point number, an integer in the range of ± (253-1).
  • bigint is used for integers of any length.
  • String is used for Strings: a string can contain 0 or more characters, so there is no separate single character type.
  • boolean , is used for , true , and , false.
  • Null is used for unknown values -- a separate type with only one null value.
  • Undefined , for undefined values -- a separate type with only one , undefined , value.
  • symbol is used for unique identifiers.
  • object is used for more complex data structures.

String string

  1. Quotation marks

In JS, strings need to be enclosed in quotation marks. The same quotation marks cannot be nested (double quotation marks cannot be nested directly)

In JavaScript, there are three ways to include strings.

  1. Double quotes: "Hello"
  2. Single quotation mark: 'Hello'
  3. Backquote: ` Hello`

Double quotation marks and single quotation marks are simple references, and there is little difference between them in JavaScript.

 

Backquotes are function extension quotation marks. They allow us to wrap variables and expressions in ${...} To embed them into a string. For example:

let name = "John";

// Embed a variable
alert( `Hello, ${name}!` ); // Hello, John!

// Embed an expression
alert( `the result is ${1 + 2}` ); // the result is 3

        ${...} The expression in is evaluated and the result becomes part of the string. Can be found in ${...} Put anything inside: variables, or arithmetic expressions, or something more complex.

In addition, backquotes allow strings to span lines: (single quotes and double quotes are not allowed)

let nameList = `Names:
 * Tom
 * Tony
 * Mary
`;
alert(nameList); // Multiline list

 

 

  2. Escape character

In the string, we can use \ as the escape character. When it represents some special symbols, we can use \ to escape

For example:

let nameList = "Names:\n Tom\n Tony\n Mary";

alert(nameList); // A multiline list

 

Escape character
SymbolExpress meaning
\nLine feed
\rEnter: not used alone. Windows text files use a combination of two characters \ R \ nto represent line breaks
\' , \"Quotation marks
\\Backslash
\tTab
\b, \f, \vBackspace, page feed, vertical labels - not used now for compatibility
\xXXUnicode characters with the given hexadecimal Unicode {XX}, for example: '\ x7A' and 'z' are the same.
\uXXXXunicode characters of UTF-16 encoded hex code XXXX, such as \ u00A9 -- are copyright symbols © unicode. It must be exactly 4 hexadecimal digits.
\u{X...XXXXXX}unicode symbol with the given UTF-32 encoding. Some rare characters are encoded with two unicode symbols, occupying 4 bytes. So we can insert long code.

 

  3. String length

The length property indicates the length of the string

for instance:

alert( `My\n`.length ); // 3

\ n is a separate "special" character, so the length is 3.

To view the length of a string, you can call the str.length property

  4. Access character

To get a character in the pos position, you can use square brackets [pos] or call the str.charAt(pos) method. The first character starts at zero:

let str = `Hello`;

// First character
alert( str[0] ); // H
alert( str.charAt(0) ); // H

// Last character
alert( str[str.length - 1] ); // o

If no character is found, [] returns undefined and charAt returns an empty string

 

In addition, you can use for Of traversal character:

for (let char of "Hello") {
  console.log(char);
}

A single character in a string cannot be changed directly!!!

  5. Change case

You can use the methods of toLowerCase() and toUpperCase() to change the case

for instance:

alert( 'Interface'.toUpperCase() ); // INTERFACE
alert( 'Interface'.toLowerCase() ); // interface

You can also change the case of a character in the string

Another example:

alert( 'Interface'[0].toLowerCase() ); // 'i'

  6. Find substring

        (1).str.indexOf()

 str.indexOf(substr,pos)

It starts with setting pos to the location, and looks for} substr in str. if it is not found, it returns - 1. Otherwise, it returns the location where the matching is successful.

let str = 'Widget with id';

alert( str.indexOf('Widget') ); // 0, because 'Widget' was found at the beginning
alert( str.indexOf('widget') ); // -1. Not found. The retrieval is case sensitive

alert( str.indexOf("id") ); // 1, "id" is at position 1 (... idget and id)

The optional second parameter "pos" allows us to retrieve from a given starting position.

For example, the first occurrence of "id" is 1. When querying the next existing location, we start from 2 #:

let str = 'Widget with id';

alert( str.indexOf('id', 2) ) // 12

There is also a similar method str.lastIndexOf(substr,pos), which searches from the end of the string to the beginning.

It lists these events in reverse order.

        (2).includes,startsWith,endsWith

str.includes(substr,pos) returns true/false according to whether substr is included in str.

If you need to detect a match, but you don't need its location, you can choose this method

for instance:

alert( "Widget with id".includes("Widget") ); // true
alert( "Hello".includes("Bye") ); // false

 

The second optional parameter to str.includes is the start of the search

Another example:

alert( "Midget".includes("id") ); // true
alert( "Midget".includes("id", 3) ); // false, no "id" from position 3

 

The methods str.startsWith(substr) and str.endsWith(substr) indicate whether the string starts or ends with substr

Another example:

alert( "Widget".startsWith("Wid") ); // true, "Widget" starts with "Wid"
alert( "Widget".endsWith("get") ); // true, "Widget" ends with "get"

  7. Get substring

         (1).str.slice(start [, end])

Returns the part of the string from start to (but not including) end

for instance:

let str = "stringify";
alert( str.slice(0, 5) ); // 'string ', substring from 0 to 5 (excluding 5)
alert( str.slice(0, 1) ); // 's', from 0 to 1, but excluding 1, so there are only characters at 0

If there is no second parameter, slice runs until the end of the string:

let str = "stringify";
alert( str.slice(2) ); // From the second position to the end

start / end can also be negative. They mean that the starting position is calculated from the end of the string:

let str = "stringify";

// Start at the fourth position on the right and end at the first position on the right
alert( str.slice(-4, -1) ); // 'gif'

        (2). str.substring(start [, end])

The part of the return string between start and end is almost the same as slice, but it allows start to be greater than end, and does not support negative parameters.

let str = "stringify";

// These are the same for substring s
alert( str.substring(2, 6) ); // "ring"
alert( str.substring(6, 2) ); // "ring"

// ... but different for slice:
alert( str.slice(2, 6) ); // "ring" (same)
alert( str.slice(6, 2) ); // "" (empty string)

        (3).str.substr(start [, length])

Returns the portion of a string of a given length starting with start.

Compared with the previous methods, this allows us to specify the length instead of the end position:

let str = "stringify";
alert( str.substr(2, 4) ); // 'ring', starting from position 2, get 4 characters

The first parameter may be a negative number from the end:

let str = "stringify";
alert( str.substr(-4, 2) ); // 'gi', get 2 characters from bit 4

 

There are two string functions:

  • str.trim() -- delete the spaces before and after the string ("trims").
  • str.repeat(n) -- repeat the string {n} times.

Topics: Javascript Front-end ECMAScript linq