Home  >  Article  >  Web Front-end  >  In-depth understanding of JavaScript String object code examples

In-depth understanding of JavaScript String object code examples

黄舟
黄舟Original
2017-03-14 15:35:25977browse

This article mainly introduces and analyzes the specific usage of the String object in JavaScript, as well as the methods related to the String object, so as to facilitate developers to make more progress in JavaScript development. Handle strings well.

1. Introduce the

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

2. Definition method

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:

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

2.2 Direct assignment (recommended)
Example:

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

3. ExampleAttribute

3.1 length: Return the number of characters in the string

var s = 'abc';
console.log(s.length); // => 3
console.log('新年快乐'.length); // => 4 :一个中文字符也计算为1个数量
console.log(''.length); // => 0 :空字符串返回0

4. Instance method

Note: The instance method of a 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 will be returned.
Parameters:

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

Return value:

{string} Returns the character at the specified position in a string; if passed Enter a non-existent position value and return an empty string

Example:

var s = 'abc';
console.log(s.charAt(1)); // => b :返回位置为1的字符
console.log(s); // => 不影响原来的数组
console.log(s.charAt(5)); // => '' :获取一个不存在位置的字符,返回一个长度为0的空字符串

4.2 charCodeAt(index): Return 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 passed Enter a position value that does not exist and return NaN

Example:

var s = 'abc';
console.log(s.charCodeAt(0)); // => 98 :字符b的Unicode编码
console.log(s.charCodeAt(5)); // => NaN :获取一个不存在位置的字符,返回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 connected string

Example:

var s = 'abc';
console.log(s.concat('d')); // => abcd
console.log(s); // => abc :不影响原先的字符串
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 starts from 0). If not found, return -1
Parameters:

①value {string}: The searched string

②startPosition {int} Optional: The starting position to start the search, the default starting position Start searching at 0

Return value:

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

Example:

var s = 'abc';
console.log(s.indexOf('b')); // => 1
console.log(s.indexOf('d')); // => -1 :未找到
console.log(s.indexOf('b', 2)); // => -1 :从位置2(第3个字符处)开始查找

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

①value {string}: The string to be searched

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

Return value:

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

Example:

var s = 'abcabc';
console.log(s.lastIndexOf('a')); // => 3 :从后往前查找
console.log(s.lastIndexOf('d')); // => -1 :未找到返回-1
console.log(s.lastIndexOf('a', 2)); // => 0 :从位置2(第3个字符处)开始往前查找

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

①value { string}: The string to be compared

Return value:

0: The instance is larger than the parameter

1: The instance is equal to the parameter

-1: The instance is smaller than the parameter

Example:

var s='abc';
console.log(s.localeCompare('ab')); // => 1 :实例比参数大
console.log(s.localeCompare('abc')); // => 0 :实例与参数相等
console.log(s.localeCompare('abd')); // => -1 :实例比参数小

4.7 match(regexp): Useregular expressionfor matching search
Parameter:

①regexp {regexp}: Regular expression, eg:/\d+/

Return value:

Depending on whether the regular expression has the attribute 'g', different results are returned; if there is no match, then Returns {null}:

① 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 parenthesis, and so on

index attribute: indicates the matching text At the beginning of the matching source

input attribute: indicates the matching source

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

Example:

// 1.单个匹配
var s = 'a1b2c3d4';
var mc = s.match(/\d+/); // => 获取第一个正则匹配的结果
if (mc != null) {
    console.log(mc.index); // => 1 :匹配结果在匹配源的起始位置
    console.log(mc.input) // => a1b2c3d4 :匹配源
    console.log(mc[0]); // => 1 :获取匹配到的结果
}
// 2.全局匹配
var mcArray = s.match(/\d+/g); // => 获取全部正则匹配的数字
if (mcArray != null) {
    for (var i = 0,len=mcArray.length; i < len; i++) {
        var mc=mcArray[i];
        console.log(mc); // => 1,2,3,4 :获取匹配到的结果
    }
}
// 3.带括号的匹配
s = &#39;a1b2c3d4&#39;;
mc = s.match(/[a-z]([1-9])/); // => 获取第一个正则匹配的结果
if (mc != null) {
    console.log(mc.index); // => 0 :匹配结果在匹配源的起始位置
    console.log(mc.input) // => a1b2c3d4 :匹配源
    console.log(mc[0]); // => a1 :序号0表示匹配到的结果
    console.log(mc[1]); // => 1 :序号1表示第一个括号内的子匹配结果
}

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)若是字符串,表示替换的字符串,匹配到字串都替换成此字符串;

字符串中的$字符有特殊的含义:

$1,$2 … $99 :表示①参从左到右圆括号的匹配子项

$& :表示整个①参匹配的子项

$$ :美元符号

2)若是函数,表示每个匹配结果都调用此函数,函数的唯一参数为匹配结果,并返回一个替换结果。

返回值:

{string} 返回一个替换后的字符串

示例:

var oldStr = &#39;a1b2c3d4&#39;;
// 1.正则匹配到【所有】数字,替换成:&#39;,&#39;逗号
var newStr = oldStr.replace(/\d+/g, &#39;,&#39;);
console.log(newStr); // => a,b,c,d,
// 2.正则匹配到【所有】数字,替换成:匹配结果 + &#39;,&#39;逗号
newStr = oldStr.replace(/\d+/g, &#39;$&,&#39;);
console.log(newStr); // => a1,b2,c3,d4,
// 3.正则匹配到【所有】数字,每个匹配结果都调用函数,并返回替换后的结果
newStr = oldStr.replace(/\d+/g, function (word) {
    if (word % 2 == 0) {
        return &#39;偶&#39;;
    }
    return &#39;奇&#39;;
});
console.log(newStr); // => a奇b偶c奇d偶

4.9 search(regexp) :返回查找正则表达式第一个匹配的位置
参数:

①regexp {regexp} :正则表达式。eg:/\d+/

返回值:

{int} 返回第一个匹配的结果的位置;若没找到匹配结果返回-1

示例:

console.log( &#39;abcd&#39;.search(/\d+/) ); // => -1 :没有找到数字
console.log( &#39;abcd1234&#39;.search(/\d+/) ); // => 4 :位置序号为4,返回第一个数字的位置

4.10  slice(start, |end):返回从字符串start位置到end前一个位置的子串
参数:

①start {int} :子串提取的开始位置索引(包括此位置的字符)。

若数字为负,表示从字符串尾部开始计算。如:-1表示倒数一个字符串,-2表示倒数第二个字符。

②end {int} 可选:子串提取的结束位置索引(不包括此位置的字符)。

若数字为负,表示从字符串尾部开始计算。如:-1表示倒数一个字符串,-2表示倒数第二个字符。

若省略此参数,返回从start位置到结束的所有字符。

注意:

子串的提取顺序是从左到有,若start索引位置大于end索引位置,将返回一个空字符串。

返回值:

{string} 返回从字符串start位置到end前一个位置的子串。

示例:

var s = &#39;abcdefg&#39;;
console.log( s.slice(1) ); // bcdefg :省略end参数,结束位置为末尾
console.log( s.slice(1, 3) ); // bc :返回从位置序号1到位置序号2(end前一个位置)的子串
console.log( s.slice(-3) ); // efg :返回从倒数第三个开始到末尾的所有字符
console.log( s.slice(-3, -1) ); // ef :返回从倒数第三个开始到第二个(end前一个位置)的所有字符

4.11 split(delimiter, |arrayLength) :将字符串按照某种分隔符切分成一个由字符串组成的数组并返回
参数:

①delimiter {regexp | string} :指定的分隔符,可以为正则表达式或字符串。

②arrayLength {int} 可选 :分割数组的长度。若省略,返回所有分割的子串。

注意:

若分隔符在字符串的第一个或最后一个,将添加一个空字符串到返回的数组。

返回值:

{ string[] } 返回一个由字符串组成的数组。

示例:

console.log( &#39;a,b,c,d,e&#39;.split(&#39;,&#39;) ); // => ["a", "b", "c", "d", "e"]
console.log( &#39;,a,b,c,d,e,&#39;.split(&#39;,&#39;) ); // => ["", "a", "b", "c", "d", "e", ""] :分隔符在最前或最后面,会添加一个空字符串
console.log( &#39;a,b,c,d,e&#39;.split(&#39;,&#39;,3) ); // => ["a", "b", "c"] :返回前3个分割的子串
console.log( &#39;a1b2c3d4e&#39;.split(/\d/) ); // => ["a", "b", "c", "d", "e"] :将数字来做为分隔符

4.12 substr(start, |wordLength):返回从字符串start位置开始计算到wordLength个长度的子串
参数:

①start {int} :子串提取的开始位置索引(包括此位置的字符)。

若数字为负,表示从字符串尾部开始计算。如:-1表示倒数一个字符串,-2表示倒数第二个字符。

②wordLength {int} 可选 :提取字符的长度。若省略此参数,返回从start位置到结束的所有字符。

返回值:

{string} 返回提取的字符串

示例:

ar s = &#39;abcdefg&#39;;
onsole.log( s.substr(0) ); // =>  abcdefg :省略第二个参数,返回从位置序号0开始,一直到最后的字符
onsole.log( s.substr(0, 3) ); // => abc :返回从位置序号0开始,计数3个字符
onsole.log( s.substr(2, 4) ); // => cdef :返回从位置序号2开始,计数4个字符
onsole.log( s.substr(-2, 3) ); // fg :返回从倒数第二个字符串开始,计数3个(超过字符长度,就只返回可统计的字符)

4.12 substr(start, |wordLength):返回从字符串start位置开始计算到wordLength个长度的子串
参数:

①start {int} :子串提取的开始位置索引(包括此位置的字符)。

若数字为负,表示从字符串尾部开始计算。如:-1表示倒数一个字符串,-2表示倒数第二个字符。

②wordLength {int} 可选 :提取字符的长度。若省略此参数,返回从start位置到结束的所有字符。

返回值:

{string} 返回提取的字符串

示例:

ar s = &#39;abcdefg&#39;;
onsole.log( s.substr(0) ); // =>  abcdefg :省略第二个参数,返回从位置序号0开始,一直到最后的字符
onsole.log( s.substr(0, 3) ); // => abc :返回从位置序号0开始,计数3个字符
onsole.log( s.substr(2, 4) ); // => cdef :返回从位置序号2开始,计数4个字符
onsole.log( s.substr(-2, 3) ); // fg :返回从倒数第二个字符串开始,计数3个(超过字符长度,就只返回可统计的字符)

4.13 substring(start, |end) :返回从字符串start位置到end前一个位置的子串
参数:

①start {int} :子串提取的开始位置索引(包括此位置的字符)。数字不能为负数,若为负数按0来处理

②end {int} 可选:子串提取的结束位置索引(不包括此位置的字符)。数字不能为负数,若为负数按0来处理

返回值:

{string} 返回从字符串start位置到end前一个位置的子串。

示例:

var s = &#39;abcdefg&#39;;
console.log( s.substring(0) ); // =>  abcdefg :省略end参数,返回从位置序号0开始,一直到最后的字符
console.log( s.substring(0, 3) ); // => abc :返回从位置序号0开始到位置序号2(②参的前一个)的字符
console.log( s.substring(2, 4) ); // => cd :返回从位置序号2开始到位置序号3(②参的前一个)的字符
console.log( s.substring(-3, 3) ); // abc :参数若为负,就按数字0来处理,所以此参数实际返回位置序号0到位置序号3的字符

4.14 toUpperCase() :将字符串转换为大写并返回

4.15 toUpperCase() :将字符串转换为小写并返回

4.16 trim() :移除字符串开头和结尾处的空白字符并返回

The above is the detailed content of In-depth understanding of JavaScript String object code examples. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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