Maison > interface Web > js tutoriel > le corps du texte

Les exemples présentent quelques méthodes courantes d'exploitation des chaînes en javaScript

WBOY
Libérer: 2022-08-04 11:41:11
avant
1375 Les gens l'ont consulté

Cet article vous apporte des connaissances pertinentes sur javascript. Il présente principalement certaines méthodes courantes de chaînes d'exploitation javaScript. L'article le présente en détail à travers un exemple de code et a une certaine valeur de référence. .

Les exemples présentent quelques méthodes courantes d'exploitation des chaînes en javaScript

[Recommandations associées : Tutoriel vidéo Javascript, front-end Web]

1 Obtenez la longueur de la chaîne

La chaîne en JavaScript a un attribut de longueur, qui peut être utilisé pour obtenir la longueur de la chaîne Longueur

const str = 'hello';
str.length   // 输出结果:5
Copier après la connexion

2. Obtenez la valeur de la position spécifiée dans la chaîne. Les méthodes charAt() et charCodeAt() peuvent obtenir la valeur de la position spécifiée via l'index :

charAt. () obtient le caractère de position spécifié ; la méthode
    charCodeAt() obtient la valeur Unicode du caractère à la position spécifiée. La méthode
  • (1) charAt()
charAt() peut renvoyer le caractère à la position spécifiée. La syntaxe est la suivante :

string.charAt(index)
Copier après la connexion

index représente la valeur d'index du caractère dans la chaîne :

const str = 'hello';
str.charAt(1)  // 输出结果:e
Copier après la connexion

La chaîne peut également obtenir directement le caractère correspondant via la valeur d'index, alors quelle est la différence entre elle et charAt() ?

const str = 'hello';
str.charAt(1)  // 输出结果:e 
str[1]         // 输出结果:e 
str.charAt(5)  // 输出结果:'' 
str[5]         // 输出结果:undefined
Copier après la connexion

Vous pouvez voir que lorsque la valeur de index n'est pas dans la plage de longueur de str, str[index] renverra undéfini et charAt(index) renverra une chaîne vide de plus, str[index] n'est pas compatible ; avec ie6-ie8, charAt( index) est compatible.

(2) charCodeAt()

charCodeAt() : Cette méthode renverra la valeur Unicode du caractère à la position d'index spécifiée. La valeur de retour est un entier compris entre 0 et 65535, indiquant le. caractère à l'index donné. Unité de code UTF-16, s'il n'y a aucun caractère à la position spécifiée, il renverra

NaN

 :

let str = "abcdefg";
console.log(str.charCodeAt(1)); // "b" --> 98
Copier après la connexion
charCodeAt():该方法会返回指定索引位置字符的 Unicode 值,返回值是 0 - 65535 之间的整数,表示给定索引处的 UTF-16 代码单元,如果指定位置没有字符,将返回 NaN

string.indexOf(searchvalue,fromindex)
Copier après la connexion

通过这个方法,可以获取字符串中指定Unicode编码值范围的字符。比如,数字0~9的Unicode编码范围是: 48~57,可以通过这个方法来筛选字符串中的数字,当然如果你更熟悉正则表达式,会更方便。

3. 检索字符串是否包含特定序列

这5个方法都可以用来检索一个字符串中是否包含特定的序列。其中前两个方法得到的指定元素的索引值,并且只会返回第一次匹配到的值的位置。后三个方法返回的是布尔值,表示是否匹配到指定的值。

注意:这5个方法都对大小写敏感!

(1)indexOf()

indexOf():查找某个字符,有则返回第一次匹配到的位置,否则返回-1,其语法如下:

let str = "abcdefgabc";
console.log(str.indexOf("a"));   // 输出结果:0
console.log(str.indexOf("z"));   // 输出结果:-1
console.log(str.indexOf("c", 4)) // 输出结果:9
Copier après la connexion

该方法有两个参数:

  • searchvalue:必需,规定需检索的字符串值;
  • fromindex:可选的整数参数,规定在字符串中开始检索的位置。它的合法取值是 0 到 string.length - 1。如省略该,则从字符串的首字符开始检索。
let str = "abcabc";
console.log(str.lastIndexOf("a"));  // 输出结果:3
console.log(str.lastIndexOf("z"));  // 输出结果:-1
Copier après la connexion

(2)lastIndexOf()

lastIndexOf():查找某个字符,有则返回最后一次匹配到的位置,否则返回-1

string.includes(searchvalue, start)
Copier après la connexion

该方法和indexOf()类似,只是查找的顺序不一样,indexOf()是正序查找,lastIndexOf()是逆序查找。

(3)includes()

includes():该方法用于判断字符串是否包含指定的子字符串。如果找到匹配的字符串则返回 true,否则返回 false。该方法的语法如下:

let str = 'Hello world!';

str.includes('o')  // 输出结果:true
str.includes('z')  // 输出结果:false
str.includes('e', 2)  // 输出结果:false
Copier après la connexion

该方法有两个参数:

  • searchvalue:必需,要查找的字符串;
  • start:可选,设置从那个位置开始查找,默认为 0。
let str = 'Hello world!';

str.startsWith('Hello') // 输出结果:true
str.startsWith('Helle') // 输出结果:false
str.startsWith('wo', 6) // 输出结果:true
Copier après la connexion

(4)startsWith()

startsWith():该方法用于检测字符串是否以指定的子字符串开始。如果是以指定的子字符串开头返回 true,否则 false。其语法和上面的includes()方法一样。

string.endsWith(searchvalue, length)
Copier après la connexion

(5)endsWith()

endsWith() Grâce à cette méthode, vous pouvez obtenir les caractères dans la plage de valeurs d'encodage Unicode spécifiée dans le chaîne. Par exemple, la plage de codage Unicode des nombres 0 à 9 est : 48 à 57. Vous pouvez utiliser cette méthode pour filtrer les nombres dans la chaîne. Bien sûr, ce sera plus pratique si vous êtes plus familier avec les expressions régulières. 3. Récupérer si une chaîne contient une séquence spécifique

Ces 5 méthodes peuvent être utilisées pour récupérer si une chaîne contient une séquence spécifique. Les deux premières méthodes obtiennent la valeur d'index de l'élément spécifié et ne renvoient que la position de la première valeur correspondante. Les trois dernières méthodes renvoient des valeurs booléennes, indiquant si la valeur spécifiée correspond.

  • Remarque : ces 5 méthodes sont toutes sensibles à la casse !
  • (1) indexOf()

indexOf() : Recherchez un certain caractère, si

est trouvé, renvoie la première position correspondante

, sinon renvoie -1, la syntaxe est la suivante :

let str = 'Hello world!';

str.endsWith('!')       // 输出结果:true
str.endsWith('llo')     // 输出结果:false
str.endsWith('llo', 5)  // 输出结果:true
Copier après la connexion

Cette méthode a deux paramètres :

🎜🎜searchvalue : obligatoire, précise la valeur de chaîne à récupérer ; 🎜🎜fromindex : paramètre entier facultatif, précise la position dans la chaîne pour lancer la recherche. Ses valeurs légales vont de 0 à string.length - 1. Si ceci est omis, la recherche commence à partir du premier caractère de la chaîne. 🎜🎜
string.concat(string1, string2, ..., stringX)
Copier après la connexion
Copier après la connexion
🎜(2) lastIndexOf()🎜🎜lastIndexOf() : recherche un certain caractère, le cas échéant, renvoie la dernière position correspondante, sinon renvoie -1🎜
let str = "abc";
console.log(str.concat("efg"));          //输出结果:"abcefg"
console.log(str.concat("efg","hijk")); //输出结果:"abcefghijk"
Copier après la connexion
Copier après la connexion
🎜Cette méthode est la même car indexOf() est similaire, sauf que l'ordre de recherche est différent. indexOf() est une recherche avant et lastIndexOf() est une recherche inversée. 🎜🎜(3) include()🎜🎜includes() : Cette méthode est utilisée pour déterminer si la chaîne contient la sous-chaîne spécifiée. Renvoie vrai si une chaîne correspondante est trouvée, faux sinon. La syntaxe de cette méthode est la suivante : 🎜
string.split(separator,limit)
Copier après la connexion
Copier après la connexion
🎜Cette méthode a deux paramètres : 🎜🎜🎜searchvalue : obligatoire, la chaîne à trouver 🎜🎜start : facultatif, définit la position à partir de laquelle commencer la recherche, la valeur par défaut est 0. 🎜🎜
let str = "abcdef";
str.split("c");    // 输出结果:["ab", "def"]
str.split("", 4)   // 输出结果:['a', 'b', 'c', 'd']
Copier après la connexion
Copier après la connexion
🎜(4) startWith()🎜🎜startsWith() : Cette méthode est utilisée pour détecter si la chaîne 🎜 commence par la sous-chaîne spécifiée 🎜. Renvoie vrai s'il commence par la sous-chaîne spécifiée, faux sinon. Sa syntaxe est la même que celle de la méthode include() ci-dessus. 🎜
str.split("");     // 输出结果:["a", "b", "c", "d", "e", "f"]
Copier après la connexion
Copier après la connexion
🎜(5) endWith()🎜🎜endsWith() : Cette méthode est utilisée pour déterminer si la chaîne actuelle 🎜 se termine par la sous-chaîne spécifiée 🎜. Renvoie vrai si la sous-chaîne transmise se trouve à la fin de la chaîne de recherche, faux sinon. La syntaxe est la suivante : 🎜
const list = "apples,bananas;cherries"
const fruits = list.split(/[,;]/)
console.log(fruits);  // 输出结果:["apples", "bananas", "cherries"]
Copier après la connexion
Copier après la connexion
🎜Cette méthode a deux paramètres : 🎜🎜🎜searchvalue : obligatoire, la sous-chaîne à rechercher 🎜🎜length : Définit la longueur de la chaîne, la valeur par défaut est la longueur de la chaîne d'origine string.length ; . 🎜🎜
string.slice(start,end)
Copier après la connexion
Copier après la connexion
🎜Vous pouvez voir que lorsque le deuxième paramètre est défini sur 5, il sera récupéré à partir des 5 premiers caractères de la chaîne, donc true sera renvoyé. 🎜🎜4. Concaténer plusieurs chaînes🎜🎜La méthode concat() est utilisée pour concaténer deux ou plusieurs chaînes. Cette méthode ne modifie pas la chaîne d'origine, mais renvoie une nouvelle chaîne concaténée avec deux chaînes ou plus. Sa syntaxe est la suivante : 🎜
string.concat(string1, string2, ..., stringX)
Copier après la connexion
Copier après la connexion

其中参数 string1, string2, ..., stringX 是必须的,他们将被连接为一个字符串的一个或多个字符串对象。

let str = "abc";
console.log(str.concat("efg"));          //输出结果:"abcefg"
console.log(str.concat("efg","hijk")); //输出结果:"abcefghijk"
Copier après la connexion
Copier après la connexion

虽然concat()方法是专门用来拼接字符串的,但是在开发中使用最多的还是加操作符+,因为其更加简单。

5. 字符串分割成数组

split() 方法用于把一个字符串分割成字符串数组。该方法不会改变原始字符串。其语法如下:

string.split(separator,limit)
Copier après la connexion
Copier après la connexion

该方法有两个参数:

  • separator:必需。字符串或正则表达式,从该参数指定的地方分割 string。
  • limit:可选。该参数可指定返回的数组的最大长度。如果设置了该参数,返回的子串不会多于这个参数指定的数组。如果没有设置该参数,整个字符串都会被分割,不考虑它的长度。
let str = "abcdef";
str.split("c");    // 输出结果:["ab", "def"]
str.split("", 4)   // 输出结果:['a', 'b', 'c', 'd']
Copier après la connexion
Copier après la connexion

如果把空字符串用作 separator,那么字符串中的每个字符之间都会被分割。

str.split("");     // 输出结果:["a", "b", "c", "d", "e", "f"]
Copier après la connexion
Copier après la connexion

其实在将字符串分割成数组时,可以同时拆分多个分割符,使用正则表达式即可实现:

const list = "apples,bananas;cherries"
const fruits = list.split(/[,;]/)
console.log(fruits);  // 输出结果:["apples", "bananas", "cherries"]
Copier après la connexion
Copier après la connexion

6. 截取字符串

substr()、substring()和 slice() 方法都可以用来截取字符串。

(1) slice()

slice() 方法用于提取字符串的某个部分,并以新的字符串返回被提取的部分。其语法如下:

string.slice(start,end)
Copier après la connexion
Copier après la connexion

该方法有两个参数:

  • start:必须。 要截取的片断的起始下标,第一个字符位置为 0。如果为负数,则从尾部开始截取。
  • end:可选。 要截取的片段结尾的下标。若未指定此参数,则要提取的子串包括 start 到原字符串结尾的字符串。如果该参数是负数,那么它规定的是从字符串的尾部开始算起的位置。

上面说了,如果start是负数,则该参数规定的是从字符串的尾部开始算起的位置。也就是说,-1 指字符串的最后一个字符,-2 指倒数第二个字符,以此类推:

let str = "abcdefg";
str.slice(1,6);   // 输出结果:"bcdef" 
str.slice(1);     // 输出结果:"bcdefg" 
str.slice();      // 输出结果:"abcdefg" 
str.slice(-2);    // 输出结果:"fg"
str.slice(6, 1);  // 输出结果:""
Copier après la connexion

注意,该方法返回的子串包括开始处的字符,但不包括结束处的字符

(2) substr()

substr() 方法用于在字符串中抽取从开始下标开始的指定数目的字符。其语法如下:

string.substr(start,length)
Copier après la connexion

该方法有两个参数:

  • start 必需。要抽取的子串的起始下标。必须是数值。如果是负数,那么该参数声明从字符串的尾部开始算起的位置。也就是说,-1 指字符串中最后一个字符,-2 指倒数第二个字符,以此类推。
  • length:可选。子串中的字符数。必须是数值。如果省略了该参数,那么返回从 stringObject 的开始位置到结尾的字串。
let str = "abcdefg";
str.substr(1,6); // 输出结果:"bcdefg" 
str.substr(1);   // 输出结果:"bcdefg" 相当于截取[1,str.length-1]
str.substr();    // 输出结果:"abcdefg" 相当于截取[0,str.length-1]
str.substr(-1);  // 输出结果:"g"
Copier après la connexion

(3) substring()

substring() 方法用于提取字符串中介于两个指定下标之间的字符。其语法如下:

string.substring(from, to)
Copier après la connexion

该方法有两个参数:

  • from:必需。一个非负的整数,规定要提取的子串的第一个字符在 string 中的位置。
  • to:可选。一个非负的整数,比要提取的子串的最后一个字符在 string 中的位置多 1。如果省略该参数,那么返回的子串会一直到字符串的结尾。

注意: 如果参数 from 和 to 相等,那么该方法返回的就是一个空串(即长度为 0 的字符串)。如果 from 比 to 大,那么该方法在提取子串之前会先交换这两个参数。并且该方法不接受负的参数,如果参数是个负数,就会返回这个字符串。

let str = "abcdefg";
str.substring(1,6); // 输出结果:"bcdef" [1,6)
str.substring(1);   // 输出结果:"bcdefg" [1,str.length-1]
str.substring();    // 输出结果:"abcdefg" [0,str.length-1]
str.substring(6,1); // 输出结果 "bcdef" [1,6)
str.substring(-1);  // 输出结果:"abcdefg"
Copier après la connexion

注意,该方法返回的子串包括开始处的字符,但不包括结束处的字符

7. 字符串大小写转换

toLowerCase() 和 toUpperCase()方法可以用于字符串的大小写转换。

(1)toLowerCase()

toLowerCase():该方法用于把字符串转换为小写。

let str = "adABDndj";
str.toLowerCase(); // 输出结果:"adabdndj"
Copier après la connexion

(2)toUpperCase()

toUpperCase():该方法用于把字符串转换为大写。

let str = "adABDndj";
str.toUpperCase(); // 输出结果:"ADABDNDJ"
Copier après la connexion

我们可以用这个方法来将字符串中第一个字母变成大写:

let word = 'apple'
word = word[0].toUpperCase() + word.substr(1)
console.log(word) // 输出结果:"Apple"
Copier après la connexion

8. 字符串模式匹配

replace()、match()和search()方法可以用来匹配或者替换字符。

(1)replace()

replace():该方法用于在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串。其语法如下:

string.replace(searchvalue, newvalue)
Copier après la connexion

该方法有两个参数:

  • searchvalue:必需。规定子字符串或要替换的模式的 RegExp 对象。如果该值是一个字符串,则将它作为要检索的直接量文本模式,而不是首先被转换为 RegExp 对象。
  • newvalue:必需。一个字符串值。规定了替换文本或生成替换文本的函数。
let str = "abcdef";
str.replace("c", "z") // 输出结果:abzdef
Copier après la connexion

执行一个全局替换, 忽略大小写:

let str="Mr Blue has a blue house and a blue car";
str.replace(/blue/gi, "red");    // 输出结果:'Mr red has a red house and a red car'
Copier après la connexion

注意: 如果 regexp 具有全局标志 g,那么 replace() 方法将替换所有匹配的子串。否则,它只替换第一个匹配子串。

(2)match()

match():该方法用于在字符串内检索指定的值,或找到一个或多个正则表达式的匹配。该方法类似 indexOf() 和 lastIndexOf(),但是它返回指定的值,而不是字符串的位置。其语法如下:

string.match(regexp)
Copier après la connexion

该方法的参数 regexp 是必需的,规定要匹配的模式的 RegExp 对象。如果该参数不是 RegExp 对象,则需要首先把它传递给 RegExp 构造函数,将其转换为 RegExp 对象。

注意: 该方法返回存放匹配结果的数组。该数组的内容依赖于 regexp 是否具有全局标志 g。

let str = "abcdef";
console.log(str.match("c")) // ["c", index: 2, input: "abcdef", groups: undefined]
Copier après la connexion

(3)search()

search()方法用于检索字符串中指定的子字符串,或检索与正则表达式相匹配的子字符串。其语法如下:

string.search(searchvalue)
Copier après la connexion

该方法的参数 regex 可以是需要在 string 中检索的子串,也可以是需要检索的 RegExp 对象。

注意: 要执行忽略大小写的检索,请追加标志 i。该方法不执行全局匹配,它将忽略标志 g,也就是只会返回第一次匹配成功的结果。如果没有找到任何匹配的子串,则返回 -1。

返回值: 返回 str 中第一个与 regexp 相匹配的子串的起始位置。

let str = "abcdef";
str.search(/bcd/)   // 输出结果:1
Copier après la connexion

9. 移除字符串收尾空白符

trim()、trimStart()和trimEnd()这三个方法可以用于移除字符串首尾的头尾空白符,空白符包括:空格、制表符 tab、换行符等其他空白符等。

(1)trim()

trim() 方法用于移除字符串首尾空白符,该方法不会改变原始字符串:

let str = "  abcdef  "
str.trim()    // 输出结果:"abcdef"
Copier après la connexion

注意,该方法不适用于null、undefined、Number类型。

(2)trimStart()

trimStart() 方法的的行为与trim()一致,不过会返回一个从原始字符串的开头删除了空白的新字符串,不会修改原始字符串:

const s = '  abc  ';

s.trimStart()   // "abc  "
Copier après la connexion

(3)trimEnd()

trimEnd() 方法的的行为与trim()一致,不过会返回一个从原始字符串的结尾删除了空白的新字符串,不会修改原始字符串:

const s = '  abc  ';

s.trimEnd()   // "  abc"
Copier après la connexion

10. 获取字符串本身

valueOf()和toString()方法都会返回字符串本身的值,感觉用处不大。

(1)valueOf()

valueOf():返回某个字符串对象的原始值,该方法通常由 JavaScript 自动进行调用,而不是显式地处于代码中。

let str = "abcdef"
console.log(str.valueOf()) // "abcdef"
Copier après la connexion

(2)toString()

toString():返回字符串对象本身

let str = "abcdef"
console.log(str.toString()) // "abcdef"
Copier après la connexion

11. 重复一个字符串

repeat() 方法返回一个新字符串,表示将原字符串重复n次:

'x'.repeat(3)     // 输出结果:"xxx"
'hello'.repeat(2) // 输出结果:"hellohello"
'na'.repeat(0)    // 输出结果:""
Copier après la connexion

如果参数是小数,会向下取整:

'na'.repeat(2.9) // 输出结果:"nana"
Copier après la connexion

如果参数是负数或者Infinity,会报错:

'na'.repeat(Infinity)   // RangeError
'na'.repeat(-1)         // RangeError
Copier après la connexion

如果参数是 0 到-1 之间的小数,则等同于 0,这是因为会先进行取整运算。0 到-1 之间的小数,取整以后等于-0,repeat视同为 0。

'na'.repeat(-0.9)   // 输出结果:""
Copier après la connexion

如果参数是NaN,就等同于 0:

'na'.repeat(NaN)    // 输出结果:""
Copier après la connexion

如果repeat的参数是字符串,则会先转换成数字。

'na'.repeat('na')   // 输出结果:""
'na'.repeat('3')    // 输出结果:"nanana"
Copier après la connexion

12. 补齐字符串长度

padStart()和padEnd()方法用于补齐字符串的长度。如果某个字符串不够指定长度,会在头部或尾部补全。

(1)padStart()

padStart()用于头部补全。该方法有两个参数,其中第一个参数是一个数字,表示字符串补齐之后的长度;第二个参数是用来补全的字符串。

如果原字符串的长度,等于或大于指定的最小长度,则返回原字符串:

'x'.padStart(1, 'ab') // 'x'
Copier après la connexion

如果用来补全的字符串与原字符串,两者的长度之和超过了指定的最小长度,则会截去超出位数的补全字符串:

'x'.padStart(5, 'ab') // 'ababx'
'x'.padStart(4, 'ab') // 'abax'
Copier après la connexion

如果省略第二个参数,默认使用空格补全长度:

'x'.padStart(4) // '   x'
Copier après la connexion

padStart()的常见用途是为数值补全指定位数,笔者最近做的一个需求就是将返回的页数补齐为三位,比如第1页就显示为001,就可以使用该方法来操作:

"1".padStart(3, '0')   // 输出结果: '001'
"15".padStart(3, '0')  // 输出结果: '015'
Copier après la connexion

(2)padEnd()

padEnd()用于尾部补全。该方法也是接收两个参数,第一个参数是字符串补全生效的最大长度,第二个参数是用来补全的字符串:

'x'.padEnd(5, 'ab') // 'xabab'
'x'.padEnd(4, 'ab') // 'xaba'
Copier après la connexion

13. 字符串转为数字

parseInt()和parseFloat()方法都用于将字符串转为数字。

(1)parseInt()

parseInt() 方法用于可解析一个字符串,并返回一个整数。其语法如下:

parseInt(string, radix)
Copier après la connexion

该方法有两个参数:

  • string:必需。要被解析的字符串。
  • radix:可选。表示要解析的数字的基数。该值介于 2 ~ 36 之间。

当参数 radix 的值为 0,或没有设置该参数时,parseInt() 会根据 string 来判断数字的基数。

parseInt("10");			  // 输出结果:10
parseInt("17",8);		  // 输出结果:15 (8+7)
parseInt("010");		  // 输出结果:10 或 8
Copier après la connexion

当参数 radix 的值以 “0x” 或 “0X” 开头,将以 16 为基数:

parseInt("0x10")      // 输出结果:16
Copier après la connexion

如果该参数小于 2 或者大于 36,则 parseInt() 将返回 NaN:

parseInt("50", 1)      // 输出结果:NaN
parseInt("50", 40)     // 输出结果:NaN
Copier après la connexion

只有字符串中的第一个数字会被返回,当遇到第一个不是数字的字符为止:

parseInt("40 4years")   // 输出结果:40
Copier après la connexion

如果字符串的第一个字符不能被转换为数字,就会返回 NaN:

parseInt("new100")     // 输出结果:NaN
Copier après la connexion

字符串开头和结尾的空格是允许的:

parseInt("  60  ")    // 输出结果: 60
Copier après la connexion

(2)parseFloat()

parseFloat() 方法可解析一个字符串,并返回一个浮点数。该方法指定字符串中的首个字符是否是数字。如果是,则对字符串进行解析,直到到达数字的末端为止,然后以数字返回该数字,而不是作为字符串。其语法如下:

parseFloat(string)
Copier après la connexion

parseFloat 将它的字符串参数解析成为浮点数并返回。如果在解析过程中遇到了正负号(+ 或 -)、数字 (0-9)、小数点,或者科学记数法中的指数(e 或 E)以外的字符,则它会忽略该字符以及之后的所有字符,返回当前已经解析到的浮点数。同时参数字符串首位的空白符会被忽略。

parseFloat("10.00")      // 输出结果:10.00
parseFloat("10.01")      // 输出结果:10.01
parseFloat("-10.01")     // 输出结果:-10.01
parseFloat("40.5 years") // 输出结果:40.5
Copier après la connexion

如果参数字符串的第一个字符不能被解析成为数字,则 parseFloat 返回 NaN。

parseFloat("new40.5")    // 输出结果:NaN
Copier après la connexion

14.如何多次复制一个字符串

JS 字符串允许简单的重复,与纯手工复制字符串不同,我们可以使用字符串的repeat方法。

const laughing = '小智'.repeat(3)
consol.log(laughing) // "小智小智小智"

const eightBits = '1'.repeat(8)
console.log(eightBits) // "11111111"
Copier après la connexion

15. 如何填充一个字符串到指定的长度

有时,我们希望字符串具有特定长度。 如果字符串太短,则需要填充剩余空间,直到达到指定的长度为止。

过去,主要还是使用库 left-pad。 但是,今天我们可以使用padStartSpadEnd方法,选择哪种方法取决于是在字符串的开头还是结尾填充字符串。

// 在开头添加 "0",直到字符串的长度为 8。
const eightBits = '001'.padStart(8, '0')
console.log(eightBits) // "00000001"

//在末尾添加“ *”,直到字符串的长度为5。
const anonymizedCode = "34".padEnd(5, "*")
console.log(anonymizedCode) // "34***"
Copier après la connexion

16.如何将字符串拆分为字符数组

有多种方法可以将字符串分割成字符数组,我更喜欢使用扩展操作符(...):

const word = 'apple'
const characters = [...word]
console.log(characters) // ["a", "p", "p", "l", "e"]
Copier après la connexion

注意,这并不总是像预期的那样工作。有关更多信息,请参见下一个技巧。

17.如何计算字符串中的字符

可以使用length属性。

const word = "apple";
console.log(word.length) // 5
Copier après la connexion

但对于中文来说,这个方法就不太靠谱。

const word = "?"
console.log(word.length) // 2
Copier après la connexion

日本汉字?返回length2,为什么? JS 将大多数字符表示为16位代码点。 但是,某些字符表示为两个(或更多)16 位代码点,称为代理对。 如果使用的是length属性,JS 告诉你使用了多少代码点。 因此,?(hokke)由两个代码点组成,返回错误的值。

那怎么去判断呢,使用解构操作符号(...)

const word = "?"
const characters = [...word]
console.log(characters.length) // 1
Copier après la connexion

这种方法在大多数情况下都有效,但是有一些极端情况。 例如,如果使用表情符号,则有时此长度也是错误的。 如果真想计算字符正确长度,则必须将单词分解为 字素簇(Grapheme Clusters) ,这超出了本文的范围,这里就不在这说明。

18.如何反转字符串中的字符

反转字符串中的字符是很容易的。只需组合扩展操作符(...)、Array.reverse方法和Array.join方法。

const word = "apple"
const reversedWord = [...word].reverse().join("")
console.log(reversedWord) // "elppa"
Copier après la connexion

和前面一样,也有一些边缘情况。遇到边缘的情况就有需要首先将单词拆分为字素簇

19. 如何将字符串中的第一个字母大写

一个非常常见的操作是将字符串的第一个字母大写。虽然许多编程语言都有一种本地方法来实现这一点,但 JS 需要做一些工作。

let word = 'apply'

word = word[0].toUpperCase() + word.substr(1)

console.log(word) // "Apple"
Copier après la connexion

另一种方法:

// This shows an alternative way
let word = "apple";

// 使用扩展运算符(`...`)拆分为字符

const characters = [...word];
characters[0] = characters[0].toUpperCase();
word = characters.join("");

console.log(word); // "Apple"
Copier après la connexion

20.如何在多个分隔符上分割字符串

假设我们要在分隔符上分割字符串,第一想到的就是使用split方法,这点,智米们肯定知道。 但是,有一点大家可能不知道,就是split可以同时拆分多个分隔符, 使用正则表达式就可以实现:

// 用逗号(,)和分号(;)分开。

const list = "apples,bananas;cherries"
const fruits = list.split(/[,;]/)
console.log(fruits); // ["apples", "bananas", "cherries"]
Copier après la connexion

21.如何检查字符串是否包含特定序列

字符串搜索是一项常见的任务。 在 JS 中,你可以使用String.includes方法轻松完成此操作。 不需要正则表达式。

const text = "Hello, world! My name is Kai!"
console.log(text.includes("Kai")); // true
Copier après la connexion

22.如何检查字符串是否以特定序列开头或结尾

在字符串的开头或结尾进行搜索,可以使用String.startsWithString.endsWith方法。

const text = "Hello, world! My name is Kai!"

console.log(text.startsWith("Hello")); // true

console.log(text.endsWith("world")); // false
Copier après la connexion

23.如何替换所有出现的字符串

有多种方法可以替换所有出现的字符串。 可以使用String.replace方法和带有全局标志的正则表达式。 或者,可以使用新的String.replaceAll方法。 请注意,并非在所有浏览器和Node.js 版本中都可用此新方法。

const text = "I like apples. You like apples."

console.log(text.replace(/apples/g, "bananas"));
// "I like bananas. You like bananas."

console.log(text.replaceAll("apples", "bananas"));
// "I lik
Copier après la connexion

24. JSON格式化和解析

JSON 不是仅限 JavaScript 的数据类型,并且广泛用于前后端数据交互。JSON.stringify() 函数用于将对象转换为 JSON 格式的字符串。通常,只需将对象作为参数即可,如下所示:

const article = {
    title: "JavaScript 字符串技巧",
    view: 30000,
    comments: null,
    content: undefined,
};
const strArticle = JSON.stringify(article); 

console.log(strArticle); // {"title":"JavaScript 字符串技巧","view":30000,"comments":null}
Copier après la connexion

从上面的代码可以看到,在 stringify 中会过滤掉 undefined 的值,但 null 值不会。

JSON.stringify() 可以接受两个可选参数,第二个参数是一个替换器,可以在其中指定要打印的键的数组或清除它们的函数。如下代码:

console.log(JSON.stringify(article, ["title", "comments"])); // {"title":"JavaScript 字符串技巧","comments":null}
console.log(JSON.stringify(article, [])); // {}
Copier après la connexion

对于一个巨大的 JSON,传递一个长数组可能影响可读性及效率。因此,可以设置替换函数并为要跳过的键返回 undefined ,如下代码:

const result = JSON.stringify(article, (key, value) =>
    key === "title" ? undefined : value
);
console.log(result); // {"view":30000,"comments":null}
Copier après la connexion

JSON.stringify() 的第三个参数通过指定缩进(在嵌套块中很有用)来格式化 JSON,可以传递一个数字来设置缩进间距,甚至可以传递一个字符串来替换空格。如下代码:

console.log(JSON.stringify(article, ["title"], "\t"));
Copier après la connexion

输出的格式如下:

{
    "title": "JavaScript 字符串技巧"
}
Copier après la connexion

还有一个 JSON.parse() 函数,它接受一个 JSON 字符串并将其转换为一个 JavaScript 对象。它还接受一个 reviver 函数,可以在返回值之前拦截对象属性并修改属性值。

const reviver = (key, value) => (key === "view" ? 0 : value);

var jsonString = JSON.stringify(article);
var jsonObj = JSON.parse(jsonString, reviver);

console.log(jsonObj); // { title: 'JavaScript 字符串技巧', view: 0, comments: null }
Copier après la connexion

25. 多行字符串和嵌入式表达式

在 JavaScript 中有三种创建字符串的方式,可以使用单引号 '' 、双引号 "" 或反引号(键盘的左上方, 1 的左边按键)。

const countries1 = "China";
const countries2 = "China";
const countries3 = `China`;
Copier après la connexion

前两种创建方式基本相同,并且可以混合和匹配以连接或添加带引号的字符串(通过使用相反的语法风格),而反引号可以对字符串进行花哨而强大的操作。

反引号也称为模板字面量,反引号在创建多行字符串和嵌入表达式时很方便。下面是如何在 JavaScript 中使用字符串插值创建多行字符串的代码:

const year = "2021";
const month = 7;
const day = 2;
const detail = `今天是${year}年${month}月${day}日,
是个不错的日子!`;

console.log(detail);
Copier après la connexion

输出的结果也换行了,如下:

今天是2021年7月2日,
是个不错的日子!

除了字符串字面量,在 ${} 中允许任何有效的表达式,它可以是一个函数调用或表达式,甚至是一个嵌套模板。

标记模板是模板字面量的一种高级形式,它允许使用一个函数来解析模板字面量,其中内嵌的表达式是参数。如下代码:

const title = "JavaScript 字符串技巧";
const view = 30000;

const detail = (text, titleExp, viewExp) => {
    const [string1, string2, string3] = [...text];
    return `${string1}${titleExp}${string2}${viewExp}${string3}`;
};

const intro = detail`本文的标题是《${title}》,当前阅读量是: ${view}`;

console.log(intro); // 文的标题是《JavaScript 字符串技巧》,当前阅读量是:30000
Copier après la connexion

26. 验证字符串数组中是否存在子字符串

查找 JavaScript 字符串中是否存在子字符串时间容易的事情,在 ES6 中,只需要使用 includes 函数。

但需要验证字符串是否存于数据中,主要数组中其中一项包含就返回 true ,如果都不包含返回 false,因此需要使用 some 函数与includes 一起使用,如下代码:

const arrayTitles = ["Javascript", "EScript", "Golang"];
const hasText = (array, findText) =>
    array.some((item) => item.includes(findText));

console.log(hasText(arrayTitles, "script")); // true
console.log(hasText(arrayTitles, "php")); // false
Copier après la connexion

【相关推荐:javascript视频教程web前端

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Étiquettes associées:
source:csdn.net
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!