Diretório de artigos
combinar、exec
- String.prototype.match
- RegExp.prototype.exec
- Sem adicionar g, o valor de retorno de ambos é o mesmo.
var str = 'asd123lkj789qwe';
var reg = /\d/;
console.log(str.match(reg))//['1', index: 3, input: 'asd123lkj789qwe', groups: undefined]
console.log(reg.exec(str)) //['1', index: 3, input: 'asd123lkj789qwe', groups: undefined]
- Adicione g, match retorna um array e exec tem uma função de memória.
var reg = /\d/g;
console.log(str.match(reg))//(6) ['1', '2', '3', '7', '8', '9']
// exec+g 有了记忆功能
console.log(reg.exec(str)) //['1', index: 3, input: 'asd123lkj789qwe', groups: undefined]
console.log(reg.exec(str)) //['2', index: 4, input: 'asd123lkj789qwe', groups: undefined]
// 直到返回null,然后再从头开始匹配
charAt,charCodeAt,fromCharCode
var str = 'a';
console.log(str.charAt(0));//a
console.log(str.charCodeAt());//97
console.log(String.fromCharCode('97'));//a
- fromCharCode imprime 26 letras
for(var i =0,res='';i<26;i++){
res+=String.fromCharCode(65+i)
}
console.log(res)
// ABCDEFGHIJKLMNOPQRSTUVWXYZ
var res = new Array(26).fill('').reduce((pre,item,index)=>{
return pre + String.fromCharCode(65+index)
},'')
console.log(res)
// ABCDEFGHIJKLMNOPQRSTUVWXYZ
var res = new Array(60).fill('').reduce((pre,item,index)=>{
return pre + String.fromCharCode(65+index)
},'').match(/[A-Za-z]/gm).join('')
console.log(res)
// ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
toLocaleLowerCase、toLocaleUpperCase、toLowerCase、toUpperCase
String.prototype.toLocaleLowerCase
String.prototype.toLocaleUpperCase
// 上面是下面的超集合,外国语建议使用上面的
String.prototype.toLowerCase
String.prototype.toUpperCase
Tags de estilo obsoletas
// 废弃的样式标签
var str = 'test style';
str.fontcolor('red') //'<font color="red">test style</font>'
str.sub() //'<sub>test style</sub>'
str.sup()
str.fixed() //'<tt>test style</tt>'
str.bold() //'<b>test style</b>'
substring、substr
// substring
// 1. substring支持倒序
console.log(str.substring(3,1)) //23
console.log(arr.slice(3,1)) //[]
// 2. 负数看做0
console.log(str.substring(-2)) //12345
-
Se o parâmetro slice for um número negativo, ele será tratado como strLength + o número negativo
-
substring extrai caracteres de indexStart para indexEnd (exclusivo). Em particular:
- Se indexStart for igual a indexEnd, substring retornará uma string vazia.
- Se indexEnd for omitido, substring extrai caracteres até o final da string.
- Se algum parâmetro for menor que 0 ou NaN, ele será tratado como 0.
- Se algum parâmetro for maior que stringName.length, ele será tratado como stringName.length.
- Se indexStart for maior que indexEnd, o efeito de execução da substring será como se os dois parâmetros fossem trocados. Veja o exemplo abaixo.
-
str.substr(início[, comprimento])
- Se start for um número negativo, ele será tratado como strLength + start
- Se start for negativo e abs(start) for maior que o comprimento da string, substr usa 0 como índice para iniciar a extração.
- O processamento de números negativos é igual ao slice
- Se o comprimento for 0 ou negativo, substr retornará uma string vazia. Se length for omitido, substr extrai caracteres até o final da string.
Este método está obsoleto.
substr não faz parte da linguagem JavaScript principal e pode ser removido no futuro. Se possível, use substring()
Métodos com o mesmo nome para strings e arrays
fatiar
- slice se comporta da mesma forma em strings e arrays
var arr = [1,2,3,4,5];
var str = '12345';
console.log(arr.slice(1)) //从索引1到末尾 (4) [2, 3, 4, 5]
console.log(arr.slice(1,3)) //区间左闭右开[) (2) [2, 3]
console.log(arr.slice(NaN))
console.log(arr.slice(null))//NaN null 无效参数=>0
console.log(arr.slice(0))//(5) [1, 2, 3, 4, 5]
console.log(arr.slice()) //(5) [1, 2, 3, 4, 5]
console.log(arr.slice(undefined))//undefined相当于没有传参数
console.log(arr.slice(-2)) //arr.length + -2 = 3 => arr.slice(3) [4, 5]
console.log(arr.slice([1])) // [2, 3, 4, 5] 会做Number的隐式转换
console.log(arr.slice('1')) // [2, 3, 4, 5]
indexof、lastIndexof
- str.indexOf(searchValue [, fromIndex])
- arr.indexOf(searchElement[, fromIndex])
// indexof 是 全等===
var arr = [1,2,3,4,5];
var str = '12345'
console.log(arr.indexOf(3)) //2
console.log(str.indexOf(3)) //2
str.indexOf(4)
str.indexOf('4')
str.indexOf([4])
// 都是3
str.indexOf(1,-2)//0 字符串把负数或不合理的值null undefined NaN当做0是一种通用方式
- str.lastIndexof
indefinido NaN => comprimento-1
var str = '1623465'
console.log(str.lastIndexOf(6,NaN));
console.log(str.lastIndexOf(6,undefined));
console.log(str.lastIndexOf(6,str.length-1));//=>str.lastIndexOf(6,NaN)
console.log(str.lastIndexOf(6))
// 都是5
console.log(str.lastIndexOf(6,null)); //-1 null看作0
inclui
substituir
-
str.replace(regexp|substr, newSubStr|função)
-
Este método não altera a string em si, apenas retorna uma nova string substituída.
-
regexp (padrão)
um objeto RegExp ou seu literal. O conteúdo correspondido por esta expressão regular será substituído pelo valor de retorno do segundo parâmetro.var str = 'plusplus' str.replace(/plus/,'+') //'+plus' //正则+g 全局匹配 str.replace(/plus/g,'+') //'++'
-
substr (padrão)
Uma string que será substituída por newSubStr. É tratado como uma string inteira, não como uma expressão regular.
Apenas a primeira partida é substituída .var str = 'plusplus' str.replace('plus','+') //'+plus'
-
newSubStr->replacement string pode inserir os seguintes nomes de variáveis especiais:
-
$$ insere um "$".
-
$& insere a substring correspondente.
-
$` Insere o conteúdo à esquerda da substring atualmente correspondente.
-
$' insere o conteúdo à direita da substring atualmente correspondente.
-
$nSe
o primeiro parâmetro for um objeto RegExp en for um número inteiro não negativo menor que 100, insira a enésima string correspondente a colchetes. Dica: a indexação começa em 1. Se o enésimo grupo não existir, o conteúdo correspondente será substituído por um literal. Por exemplo, se o terceiro grupo não existir, o conteúdo correspondente será substituído por “$3”. -
$<Name>
Aqui Nome é um nome de grupo. Se não houver agrupamento (ou correspondência) na expressão regular, esta variável será tratada como uma string vazia. Disponível apenas em navegadores que suportam captura de grupo nomeado.
-
-
Trocando duas palavras em uma string
O exemplo a seguir demonstra como trocar as posições de duas palavras em uma string. Este script usa $1 e $2 em vez de texto de substituição.var re = /(\w+)\s(\w+)/g; var str = "John Smith"; //str.match(re) //['John Smith'] var newstr = str.replace(re, "$2, $1"); // Smith, John console.log(newstr);
var re = /(\w+)\s(\w+)/g; var str = "John Smith"; //str.match(re) //['John Smith'] var newstr = str.replace(re, function($,$1,$2){ // $,$1,$2 参数名可以为其他名字 //$1,$2 代表第一个二个子表达式 console.log($,$1,$2); return $2+' '+$1 }); // Smith, John console.log(newstr); //Smith John
-
Coloque em maiúscula
var str = 'js-plus-plus' var reg = /-(\w)/g ///-\w/g var str1 = str.replace(reg,function($,$1){ console.log($,$1) //$1是子表达式 return $1.toUpperCase() }) console.log(str1) //jsPlusPlus
-
mudar para sublinhar
var str = 'jsPlusPlus' var reg = /([A-Z])/g ///-\w/g //str.match(reg) //['P', 'P'] var str1 = str.replace(reg,function($,$1){ console.log($,$1) //$1是子表达式 return '-'+$1.toLowerCase() }) console.log(str1) //js-plus-plus
-
xxyyzz->XxYyZz
//1. var str = 'xxyyzz' var reg = /(\w)\1(\w)\2(\w)\3/g //str.match(reg) //['xxyyzz'] var str1 = str.replace(reg,function($,$1,$2,$3){ return $1.toUpperCase() + $1 + $2.toUpperCase() + $2 + $3.toUpperCase() + $3 }) console.log(str1) //XxYyZz //2. var str = 'xxyyzz' var reg = /(\w)\1/g //str.match(reg) //['xxyyzz'] var str1 = str.replace(reg,function($,$1){ return $1.toUpperCase() + $1 }) console.log(str1) //XxYyZz
-
Combine símbolos regulares
var str = 'aa\\bb\\cc' //'aa\bb\cc' // var reg = /\/; //语法错误 要匹配正则语法中的转义字符需要转移 var reg = /\\/g; // str.match(reg) //(2) ['\', '\']
-
Remover duplicatas
var str = 'aaabbbbbcccccc' str.replace(/(\w)\1*/g,'$1') //'abc' str.match(/(\w)\1*/g) //(3) ['aaa', 'bbbbb', 'cccccc']
-
Divida o número zero em três dígitos
var str = '10000' str.replace(/(000)/g,'$1,') //'1000,0'
-
Divida os números por três dígitos
var str = '123456789' str.replace(/(\d\d\d)/g,'$1,') //'123,456,789,' //非单词边界的判断 var str = '123456789' str.replace(/(\d\d\d)\B/g,'$1,') //'123,456,789' // var str = '1234567890' //str.match(/(?=(\B)(\d{3})+$)/g) //(3) ['', '', ''] str.replace(/(?=(\B)(\d{3})+$)/g,'$1,') //'1,234,567,890' // 以空字符为主体,到末尾结束,中间三个数字为一组出现了一次或多次 // 找到符合条件的空字符+逗号 // '1234567890'.replace(/(?=(\B)(\d{3})+$)/g,',') // 不匹配开头边界出的字符
-
início da partida
'abcdef'.replace(/(?=(\b\w+))/g,'1')
-
Correspondência de modelos de colchetes duplos
var str = 'My name is { {name}}, I\'m { {age}} years old' // var reg = /{ {.*}}/g // ["{ {name}}, I'm { {age}}"] 贪婪匹配 // var reg = /{ {.*?}}/g // ['{ {name}}', '{ {age}}'] 加?是为了非贪婪匹配 var reg = /{ {(.*?)}}/g 子表达式 str.match(reg) var str1 = str.replace(reg,function(node,key){ console.log(node,key) // { {name}} name // { {age}} age return { name:'Jenny', age:26 }[key] }) // (2) ['{ {name}}', '{ {age}}'] // "My name is Jenny, I'm 26 years old"
-
Substituição de modelo HTML
<!DOCTYPE html> <html lang="en"> <body> <div id="wrap"> <h1>{ {title}}</h1> <p>{ {content}}</p> </div> </body> <script> var dom = document.getElementById("wrap"); var reg = /{ {(.*?)}}/g var str1 = dom.innerHTML.replace(reg,function(node,key){ return { title:'自我介绍', content:'我是一只无忧无虑的鱼' }[key] }) dom.innerHTML = str1; </script> </html>
-
número inteiro negativo
/^-\d+$/.test('-123')
- número inteiro positivo
/^[+|\d]{1,}/.test('2')
- inteiro
/^-?\d+$/.test('-123')
- Correspondência
var reg = /^([A-z0-9_-])+\@([A-z0-9_\-\.]+\.([A-z]{2,4}))$/
// var reg = /^[A-z0-9_-]+\@[A-z0-9_\-\.]+\.[A-z]{2,4}$/
var email = '[email protected]'
reg.test(email)
email.match(reg)
// ['[email protected]', '5', 'qq.com', 'com', index: 0, input: '[email protected]', groups: undefined]
// 子表达式不捕获分组
- data
/^\d{4}-\d{2}-\d{2}$/.test('1994-12-22')
/^\d{
4}([-\.])\d{
2}\1\d{
2}$/.test('1994-12-22')
/^\d{
4}([-\.])(0[1-9]|1[0-2])\1\d{
2}$/.test('1994-12-22')