string

writing

Unlike OC, strings in JavaScript can be expressed in either single or double quotes and can be nested, that is, inside a single quoted string, double quotes can be used. Inside a string, single quotes can be used. However, when single quotes are used inside single quotes, \ escape is required, as is the case when double quotes are used inside double quotes.

Join operator (+)

Similar to Swift, strings can be concatenated with +.

Strings and Arrays

Strings can be thought of as an array of characters, so you can use the square bracket operator of the array to return a character at a position (position numbering starting at 0).

var s = 'hello';
s[0] // "h"

// Use the square brackets operator directly on strings
'hello'[1] // "e"

// If the number in square brackets exceeds the length of the string, or if there are no numbers in square brackets at all, undefined is returned.
'abc'[3] // undefined
'abc'[-1] // undefined
'abc'['x'] // undefined
Copy the code

Note that strings cannot modify (add, delete, change) internal characters

Character set

JavaScript uses the Unicode character set, allowing Unicode code points to be used to represent characters directly in programs, as well as variable names. When output to the user, all characters are converted to literal form.

var s = '\u00A9';
s / / "©"

var f\u006F\u006F = 'abc';
foo // "abc"
Copy the code

Base64 transcoding

Base64 is an encoding method that converts any value into 64 printable characters: 0 to 9, A to Z, A to Z, + and /. The main purpose of using it is not to encrypt, but to avoid special characters and simplify the processing of the program. Here are two scenarios for using Base64:

  1. Text contains some non-printable characters. For example, ASCII characters 0 to 31 cannot be printed, so you can use Base64 encoding to convert them into printable characters.
  2. You need to pass binary data in text format, using Base64 encoding.

JavaScript natively provides two Base64-related methods.

  • Btoa () : Any value is converted to Base64 encoding
  • Atob () : Base64 encoding is converted to the original value
var string = 'Hello World! ';
btoa(string) // "SGVsbG8gV29ybGQh"
atob('SGVsbG8gV29ybGQh') // "Hello World!"
Copy the code

It is important to note that these two methods will generate an error when passing a non-ASCII code directly, so you need to transcode non-ASCII characters first

btoa('hello') / / an error

// Convert methods
function b64Encode(str) {
  return btoa(encodeURIComponent(str));
}

function b64Decode(str) {
  return decodeURIComponent(atob(str));
}

b64Encode('hello') // "JUU0JUJEJUEwJUU1JUE1JUJE"
b64Decode('JUU0JUJEJUEwJUU1JUE1JUJE') // "Hello"
Copy the code