RegExp - Evaluation Functions

! Content: 正規表示式、可用的方法

正規表示式

A regular expression is an object that describes a pattern of characters.
Regular expressions are used to perform pattern-matching and “search-and-replace” functions on text

首先先訂定一個pattern - /pattern/modifiers

1
2
3
4
5
6
7
8
9
10
11
12
let re;
re = /hello/
re = /hello/i; // i = case insensitive

/** modifier **/
// i => case insensitive
// g => Perform a global match
(find all matches rather than stopping after the first match)
// m => Perform multiline matching

console.log(re) // /hello/i;
console.log(re.sourse) //hello

可以運用的方法

exec() - Return result in an array or null
is used to retrieve the match of a regular expression in a string.
這個pattern是否有在這個字串裡,有則回陣列,無則回null

1
2
3
4
const result = re.exec('hello world')
console.log(result)
// ["hello", index: 0, input: "hello world", groups: undefined]
// index 是第幾個位置開始符合

test() - Return true or false

1
2
3
const result = re.test('Hello')
console.log(result)
// true

match() - Return result array or null
retrieves the specified value within a string or finds a match for one or more regular expressions.
這個字串是否有符合這個pattern,有則回陣列,無則回null

1
2
3
4
const str = 'Hello There';
const result = str.match(re)
console.log(result)
//["Hello", index: 0, input: "Hello There", groups: undefined]

search() - Return index of the first match if not found return -1

1
2
3
4
const str = 'dd Hello There'
const result = str.search(re)
console.log(result)
// 3

replace() - Return new string with some or all matchs of a pattern

1
2
3
4
const str = 'Hello There'
const newStr = str.replace(re, 'Hi')
console.log(newStr)
// Hi There