Methods of strings in regular expressions (search; match; replace)

1.search

Syntax: string.search(regular)
Found: returns the first occurrence of the subscript
not found: returns -1

<script>
        // 1. search
        const reg = /\d{3}/
        const str1 = '你好123QF456'
        const str2 = '你好'

        console.log(str1.search(reg))   // 返回的是首次出现的下标2
        console.log(str2.search(reg))   // 没有找到, 所以返回的是 -1
</script>

2.match

Syntax: string.match (regular)
Function:
1. When the regex does not add the modifier g, the function is similar to that of the regex.exec()
capture, it is an array, and the position of the array subscript 0 is the captured value.
When capturing multiple times, each time They all start to capture from subscript 0,
and return a null when not captured.
2. When the modifier g is added to
the regex, what is captured is an array, and the members in the array are each captured value.
When each value is not captured, return a null

<script>
        const reg = /\d{3}/
        const reg1 = /\d{3}/g
        const str1 = '你好123QF456'
        const str2 = '你好'

        console.log(str1.match(reg))    // ['123', index: 2, input: '你好123QF456', groups: undefined]
        console.log(str2.match(reg))    // 没有找到, 返回一个 null

        console.log(str1.match(reg1))    // ['123', '456']
        console.log(str2.match(reg1))   // 没有找到, 返回一个 null

</script>

3.replace

Syntax: string.replace(regular, characters to be replaced)
Function: Find the corresponding character through regularization and replace it

<script>
        const reg = /\d{3}/
        const reg1 = /\d{3}/g
        const str1 = '你好123QF456'
        const str2 = '你好'

        console.log(str1.replace(reg, '***'))  // 你好***QF456
        console.log(str1.replace(reg1, '***'))  //你好***QF***
        console.log(str2.replace(reg, '***'))  //你好
        console.log(str2.replace(reg1, '***'))  //你好
</script>

Guess you like

Origin blog.csdn.net/weixin_48649246/article/details/127855439