JS-正则

52 阅读1分钟

1、typeof

let sym = Symbol('123')
console.log( typeof sym)//symbol
console.log(typeof NaN)//number
  1. 对于简单的基本类型(如字符串、数字、布尔值和未定义值),JavaScript 引擎可以直接根据其存储方式确定类型,并返回相应的字符串。
  2. 对于对象、函数和 null,JavaScript 引擎通常会检查值的类型标记或类型标志,并相应地返回 "object"、"function" 或 "object"(对于 null)。

2、toString valueOf

let arr = [1,2,3] //toString:1,2,3.lenght:5

let obj = {
    name:'keke',
    age:'25'
}//toString: [object Object]  valueOf:{name,age}
let arr  = [1,2,3] //toString:1,2,3.lenght:5  valueOf:[1,2,3]

3、正则

3.1、基本语法

  1. {n,m}
  2. /g
  3. match()
  4. [123]
  5. [1-6a-fG-M]
  6. [^123]
  7. [\d\D] [\w\W] [\s\S]
  8. \d \w

3.2、量词匹配

  1. +至少一次
  2. * 0次或无数次
  3. ?只要满足条件就不继续匹配 var regex = /id=".*?"/
let regx2 = /abc{1,3}/
let str2 = 'abc abccccc'
console.log(str2.match(regx2))
//[ 'abc', index: 0, input: 'abc abccccc', groups: undefined ]
// 加上g全局匹配 [ 'abc', 'abccc' ]

3.3、匹配颜色-时间-id

/匹配颜色
let color = /#[0-9a-fA-F]{6}|[0-9a-fA-F]{3}/g
let str3 = '#000 #aaa #000000'
console.log(str3.match(color))

//匹配时间
let time = /([01][0-9]|2[0-4]):[0-5][0-9]/g
//注意把或匹配的组加括号
let timeStr = '03:56 23:09'
console.log(timeStr.match(time))

//匹配id
var regex = /id=".*?"/
var string = '<div id="container" class="main"></div>';
console.log(string.match(regex)[0]); 
// => id="container" class="main"

3.4、位置匹配

3.4.1、匹配开头结尾

//匹配开头结尾
let string2 = "hello"
let regx2 = /^|$/g
let newStr = string2.replace(regx2,'#')
console.log(newStr)
  1. ^表示开头 $表示结尾
  2. string.replace不改变原来的字符串,返回新的字符串

3.4.2、匹配单词边界

var result = "[JS] Lesson_01.mp4".replace(/\b/g, '#');
console.log(result); 
// => "[#JS#] #Lesson_01#.#mp4#"

\b表示单词边界