ReasonJun

javascript : Regular expression (test, match, replace) 본문

Frontend/Javasciprt

javascript : Regular expression (test, match, replace)

ReasonJun 2023. 6. 9. 00:21
728x90

Regular expressions, often referred to as regex or regexp, are powerful tools for pattern matching and manipulating text in various programming languages, including JavaScript. A regular expression is a sequence of characters that defines a search pattern. It consists of a combination of ordinary characters and special characters (metacharacters) that have special meaning within the pattern.

// Regular expression (RegExp)

// search
// replace
// extract

//* constructor
// new RegExp('expression', 'options')

//* literal
// /expression/options

const str = `the the.
The wow amazing the.`;

const regexp = new RegExp('the', 'gi'); // option : 'g' 'gi'
const regexp1 = /the/gi;

console.log(str.match(regexp)); // [ 'the', 'the', 'The', 'the' ]

// regular_expression.test(string) - match or not
// string.match(regex) - Returns an array of matched characters
// string.replace(regex, replace) - Replace matching characters

const regexp2 = /fox/gi;

console.log(regexp2.test(str)); // false
console.log(str.match(regexp2)); // null
console.log(str.replace(regexp2, 'cat')); // the the The wow amazing the

// g - match any character (global)
// i - English case insensitive (ignore case)
// m - multi line match, each line counts as start and end!

// \\  = escape character 

console.log(str.match(/the/));
console.log(str.match(/the/g)); // [ 'the', 'the', 'the' ]
console.log(str.match(/the/gi)); // [ 'the', 'the', 'The', 'the' ]
console.log(str.match(/\\.$/gi)); // [ '.' ]
console.log(str.match(/\\.$/gim)); // [ '.', '.' ]
728x90

'Frontend > Javasciprt' 카테고리의 다른 글

What is different 'class' and 'object' in javascript?  (0) 2023.06.10
javascript : regexp pattern  (0) 2023.06.09
javascript : Web API (location)  (0) 2023.06.09
javascript : Web API (history)  (0) 2023.06.09
javascript : Web APIs (storage)  (0) 2023.06.09
Comments