Home > Web Front-end > JS Tutorial > A Deep Dive into JavaScript String Objects_The Basics

A Deep Dive into JavaScript String Objects_The Basics

WBOY
Release: 2016-05-16 16:10:56
Original
1410 people have browsed it

String string object

1. Introduction

String object, perform operations on strings, such as intercepting a substring, searching for strings/characters, converting case, etc.

2. Definition

2.1 new String(Value) constructor: returns a String object whose content is Value
Parameters:

①value {String}: String

Return value:

{String object} returns a String object whose content is Value

Example:

Copy code The code is as follows:

var demoStr = new String('abc');
console.log(typeof demoStr); // => object
console.log(demoStr); // => abc

2.2 Direct assignment (recommended)
Example:

Copy code The code is as follows:

var demoStr = 'abc';
console.log(typeof demoStr); // string
console.log(demoStr); // => abc

3. Instance attributes

3.1 length: Returns the number of characters in the string

Copy code The code is as follows:

var s = 'abc';
console.log(s.length); // => 3
console.log('Happy New Year'.length); // => 4: A Chinese character is also counted as a quantity
console.log(''.length); // => 0: empty string returns 0

4. Instance methods

Note: The instance method of string does not change the string itself, but only returns the result of the operation.

4.1 charAt(index): Returns the character at the specified position in a string. The number starts from 0. If a non-existent value is passed in, an empty string is returned
Parameters:

①index {int}: Position index, calculated from 0

Return value:

{string} returns the character at the specified position in a string; if a non-existent position value is passed in, an empty string is returned

Example:

Copy code The code is as follows:

var s = 'abc';
console.log(s.charAt(1)); // => b: Returns the character at position 1
console.log(s); // => Does not affect the original array
console.log(s.charAt(5)); // => '': Get a character at a non-existent position and return an empty string with a length of 0

4.2 charCodeAt(index): Returns the Unicode encoding of the character at the specified position in a string
Parameters:

①index {int}: Position index, calculated from 0

Return value:

{number} Returns the Unicode encoding of the character at the specified position in a string; if a non-existent position value is passed in, NaN

is returned

Example:

Copy code The code is as follows:

var s = 'abc';
console.log(s.charCodeAt(0)); // => 98: Unicode encoding of character b
console.log(s.charCodeAt(5)); // => NaN: Get a character that does not exist and return NaN

4.3 concat(value1, value2 ... valueN): Concatenate one or more strings and return the concatenated string
Parameters:

①value1,value2 ... valueN {string}: one or more strings

Return value:

{string} Returns the concatenated string

Example:

Copy code The code is as follows:

var s = 'abc';
console.log(s.concat('d')); // => abcd
console.log(s); // => abc: does not affect the original string
console.log(s.concat('d', 'e')); // => abcde

4.4 indexOf(value, |startPosition): Find a string or character from front to back in the instance and return the found position (counting from 0). If not found, return -1
Parameters:

①value {string}: Search string

②startPosition {int} Optional: the starting position to start searching, the default is to start searching from position 0

Return value:

{int} Returns the found position (counting from 0). If not found, return -1

Example:

Copy code The code is as follows:

var s = 'abc';
console.log(s.indexOf('b')); // => 1
console.log(s.indexOf('d')); // => -1 :
not found console.log(s.indexOf('b', 2)); // => -1: Start searching for
from position 2 (the 3rd character)

4.5 lastIndexOf(value, |startPosition): Search for a string or character from back to front in the instance and return the found position (counting from 0). If not found, return -1
Parameters:

①value {string}: Search string

②startPosition {int} Optional: the starting position to start searching, the default is to start searching from the end

Return value:

{int} Returns the found position (counting from 0). If not found, return -1

Example:

Copy code The code is as follows:

var s = 'abcabc';
console.log(s.lastIndexOf('a')); // => 3: Search from back to front
console.log(s.lastIndexOf('d')); // => -1: Not found returns -1
console.log(s.lastIndexOf('a', 2)); // => 0: Search forward
starting from position 2 (the 3rd character)

4.6 localeCompare(value): Compare the instance with the parameter and return the comparison result
Parameters:

①value {string}: The string to be compared

Return value:

0: The instance is larger than the parameter

 1: Instance and parameter are equal

-1: The instance is smaller than the parameter

Example:

Copy code The code is as follows:

var s='abc';
console.log(s.localeCompare('ab')); // => 1: The instance is larger than the parameter
console.log(s.localeCompare('abc')); // => 0: instance and parameter are equal
console.log(s.localeCompare('abd')); // => -1: The instance is smaller than the parameter

4.7 match(regexp): Use regular expressions for matching search
Parameters:

①regexp {regexp}: regular expression, eg: /d /

Return value:

According to whether the regular expression has the attribute 'g', different results are returned; if there is no match, {null} is returned:

①The regular expression does not have the attribute 'g', performs a match, and returns a {single match} result object. The object contains the following attributes:

Array serial number: indicates the matching result, 0 is the matching text, 1 is the matching result of the first parenthesis from the right to the right, 2 is the second parentheses, and so on

Index attribute: indicates that the matching text is at the starting position of the matching source

Input attribute: indicates the matching source

②The regular expression has the attribute 'g', performs global matching, finds all matching objects in the string, and returns a {string array}: the array element contains each matching object in the string, excluding the regular expression in parentheses The string also does not provide index and input attributes.

Example:

Copy code The code is as follows:

// 1. Single match
var s = 'a1b2c3d4';
var mc = s.match(/d /); // => Get the result of the first regular match
if (mc != null) {
console.log(mc.index); // => 1: The matching result is at the starting position of the matching source
console.log(mc.input) // => a1b2c3d4: matching source
console.log(mc[0]); // => 1: Get the matching result
}
// 2. Global matching
var mcArray = s.match(/d /g); // => Get all regular matching numbers
if (mcArray != null) {
for (var i = 0,len=mcArray.length; i < len; i ) {
      var mc=mcArray[i];
console.log(mc); // => 1,2,3,4: Get the matching results
}
}
// 3. Matching with brackets
s = 'a1b2c3d4';
mc = s.match(/[a-z]([1-9])/); // => Get the result of the first regular match
if (mc != null) {
console.log(mc.index); // => 0: The matching result is at the starting position of the matching source
console.log(mc.input) // => a1b2c3d4: matching source
console.log(mc[0]); // => a1: Serial number 0 indicates the matched result
console.log(mc[1]); // => 1: Serial number 1 represents the sub-matching result in the first bracket
}

4.8 replace(regexp, replaceStr): Replace the substring matched by the regular expression and return the replaced string
Parameters:

①regexp {regexp}: Regular expression. eg:/d/

②replaceStr {string | function}:

1) If it is a string, it means the replacement string, and all matched strings will be replaced with this string;

The $ character in a string has special meaning:

$1,$2 ... $99: Indicates the matching sub-items of ①parameters from left to right parentheses

$&: Indicates the sub-items matched by the entire ① parameter

$$: dollar sign

2) If it is a function, it means that this function is called for each matching result. The only parameter of the function is the matching result, and a replacement result is returned.

Return value:

{string} returns a replaced string

Example:

Copy code The code is as follows:

var oldStr = 'a1b2c3d4';
// 1. If the regular match matches [all] numbers, replace them with: ',' comma
var newStr = oldStr.replace(/d /g, ',');
console.log(newStr); // => a,b,c,d,
// 2. The regular match matches [all] numbers and replaces them with: matching result ',' comma
newStr = oldStr.replace(/d /g, '$&,');
console.log(newStr); // => a1,b2,c3,d4,
// 3. The regular match matches [all] numbers, calls the function for each matching result, and returns the replaced result
newStr = oldStr.replace(/d /g, function (word) {
If (word % 2 == 0) {
         return 'even';
}
Return 'odd';
});
console.log(newStr); // => a odd b even c odd d even

4.9 search(regexp): Returns the position where the first match of the regular expression is found
Parameters:

①regexp {regexp}: Regular expression. eg:/d/

Return value:

{int} Returns the position of the first matching result; if no matching result is found, -1 is returned

Example:

Copy code The code is as follows:

console.log( 'abcd'.search(/d /) ); // => -1 : Number
not found console.log( 'abcd1234'.search(/d /) ); // => 4: The position number is 4, return the position of the first number

4.10 slice(start, |end): Returns the substring from the start position of the string to the position before end
Parameters:

①start {int}: The starting position index of substring extraction (including the character at this position).

If the number is negative, it means counting from the end of the string. For example: -1 represents the last string, -2 represents the second to last character.

②end {int} Optional: The end position index of substring extraction (excluding the character at this position).

If the number is negative, it means counting from the end of the string. For example: -1 represents the last string, -2 represents the second to last character.

If this parameter is omitted, all characters from the start position to the end will be returned.

Note:

The order of extracting substrings is from left to end. If the start index position is greater than the end index position, an empty string will be returned.

Return value:

{string} returns the substring from the start position of the string to the position before the end.

Example:

Copy code The code is as follows:

var s = 'abcdefg';
console.log( s.slice(1) ); // bcdefg: omit the end parameter, the end position is the end
console.log( s.slice(1, 3) ); // bc: Return the substring from position number 1 to position number 2 (end the previous position)
console.log( s.slice(-3) ); // efg: Returns all characters starting from the third to the end
console.log( s.slice(-3, -1) ); // ef: Returns all characters
starting from the third to last to the second (the previous position of end)

4.11 split(delimiter, |arrayLength): Split the string into an array of strings according to a certain delimiter and return
Parameters:

①delimiter {regexp | string}: The specified delimiter, which can be a regular expression or a string.

②arrayLength {int} Optional: The length of the split array. If omitted, all split substrings are returned.

Note:

If the delimiter is at the first or last character of the string, an empty string will be added to the returned array.

Return value:

{ string[] } Returns an array consisting of strings.

Example:

Copy code The code is as follows:

console.log( 'a,b,c,d,e'.split(',') ); // => ["a", "b", "c", "d", "e"]
console.log( ',a,b,c,d,e,'.split(',') ); // => ["", "a", "b", "c", "d" , "e", ""]: If the delimiter is at the beginning or end, an empty string
will be added console.log( 'a,b,c,d,e'.split(',',3) ); // => ["a", "b", "c"] : Return the first 3 splits Substring of
console.log( 'a1b2c3d4e'.split(/d/) ); // => ["a", "b", "c", "d", "e"] : Use numbers as separators

4.12 substr(start, |wordLength): Returns a substring starting from the start position of the string to wordLength lengths
Parameters:

①start {int}: The starting position index of substring extraction (including the character at this position).

If the number is negative, it means counting from the end of the string. For example: -1 represents the last string, -2 represents the second to last character.

②wordLength {int} Optional: Extract the length of characters. If this parameter is omitted, all characters from the start position to the end are returned.

Return value:

{string} returns the extracted string

Example:

Copy code The code is as follows:

ar s = 'abcdefg';
onsole.log( s.substr(0) ); // => abcdefg: Omit the second parameter and return the character starting from position number 0 to the last character
onsole.log( s.substr(0, 3) ); // => abc: Return starting from position number 0, counting 3 characters
onsole.log( s.substr(2, 4) ); // => cdef: Return starting from position number 2, counting 4 characters
onsole.log( s.substr(-2, 3) ); // fg: Return starting from the penultimate string, counting 3 (if the character length exceeds, only countable characters will be returned)

4.13 substring(start, |end): Returns the substring from the start position of the string to the position before end
Parameters:

①start {int}: The starting position index of substring extraction (including the character at this position). The number cannot be negative. If it is a negative number, it will be processed as 0

②end {int} Optional: The end position index of substring extraction (excluding the character at this position). The number cannot be negative. If it is a negative number, it will be processed as 0

Return value:

{string} returns the substring from the start position of the string to the position before the end.

Example:

Copy code The code is as follows:

var s = 'abcdefg';
console.log( s.substring(0) ); // => abcdefg: Omit the end parameter and return the character starting from position number 0 to the last character
console.log( s.substring(0, 3) ); // => abc: Returns characters
starting from position number 0 to position number 2 (the previous one of ② parameter) console.log( s.substring(2, 4) ); // => cd: Returns the characters
starting from position number 2 to position number 3 (the previous one of ② parameter) console.log( s.substring(-3, 3) ); // abc: If the parameter is negative, it will be processed as the number 0, so this parameter actually returns the characters from position number 0 to position number 3

4.14 toUpperCase(): Convert the string to uppercase and return
4.15 toUpperCase(): Convert the string to lowercase and return
4.16 trim(): remove whitespace characters at the beginning and end of the string and return

The above is the entire content of this article. I hope that through this article, everyone can have a new understanding of the String object in JavaScript.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template