--- title: RegExp slug: Web/JavaScript/Reference/Global_Objects/RegExp translation_of: Web/JavaScript/Reference/Global_Objects/RegExp ---
The RegExp
objek digunakan untuk pencocokan teks dengan pola.
Untuk pengantar ekspresi reguler, baca bab Ekspresi Reguler di Panduan JavaScript .
Ada dua cara untuk membuat RegExp
objek: notasi literal dan konstruktor .
Tiga ekspresi berikut membuat ekspresi reguler yang sama:
/ab+c/i
new RegExp(/ab+c/, 'i') // literal notation
new RegExp('ab+c', 'i') // constructor
Notasi literal menghasilkan kompilasi dari ekspresi reguler ketika ekspresi dievaluasi. Gunakan notasi literal ketika ekspresi reguler akan tetap konstan. Misalnya, jika Anda menggunakan notasi literal untuk membuat ekspresi reguler yang digunakan dalam satu lingkaran, ekspresi reguler tidak akan dikompilasi ulang pada setiap iterasi.
Konstruktor objek ekspresi reguler — misalnya, new RegExp('ab+c')
—menghasilkan kompilasi runtime dari ekspresi reguler. Gunakan fungsi konstruktor ketika Anda tahu pola ekspresi reguler akan berubah, atau Anda tidak tahu pola dan mendapatkannya dari sumber lain, seperti input pengguna.
Dimulai dengan ECMAScript 6, new RegExp(/ab+c/, 'i')
tidak lagi melempar a TypeError
( "can't supply flags when constructing one RegExp from another"
) ketika argumen pertama adalah a RegExp
dan flags
argumen kedua hadir. Sebagai RegExp
gantinya, argumen baru dibuat.
Saat menggunakan fungsi konstruktor, aturan pelolosan string normal (mendahului karakter khusus \
ketika disertakan dalam string) diperlukan.
Misalnya, yang berikut ini setara:
let re = /\w+/
let re = new RegExp('\\w+')
Perhatikan bahwa beberapa RegExp
properti memiliki nama panjang dan pendek (seperti Perl). Kedua nama selalu merujuk pada nilai yang sama. (Perl adalah bahasa pemrograman tempat JavaScript memodelkan ekspresi regulernya.). Lihat juga properti yang sudah usang RegExp
.
RegExp()
RegExp
objek baru .get RegExp[@@species]
RegExp.lastIndex
RegExp.prototype.flags
RegExp
object.RegExp.prototype.dotAll
.
matches newlines or not.RegExp.prototype.global
RegExp.prototype.ignoreCase
RegExp.prototype.multiline
RegExp.prototype.source
RegExp.prototype.sticky
RegExp.prototype.unicode
RegExp.prototype.compile()
RegExp.prototype.exec()
RegExp.prototype.test()
RegExp.prototype.toString()
Object.prototype.toString()
method.RegExp.prototype[@@match]()
RegExp.prototype[@@matchAll]()
RegExp.prototype[@@replace]()
RegExp.prototype[@@search]()
RegExp.prototype[@@split]()
The following script uses the replace()
method of the String
instance to match a name in the format first last and output it in the format last, first.
In the replacement text, the script uses $1
and $2
to indicate the results of the corresponding matching parentheses in the regular expression pattern.
let re = /(\w+)\s(\w+)/
let str = 'John Smith'
let newstr = str.replace(re, '$2, $1')
console.log(newstr)
This displays "Smith, John"
.
The default line ending varies depending on the platform (Unix, Windows, etc.). The line splitting provided in this example works on all platforms.
let text = 'Some text\nAnd some more\r\nAnd yet\rThis is the end'
let lines = text.split(/\r\n|\r|\n/)
console.log(lines) // logs [ 'Some text', 'And some more', 'And yet', 'This is the end' ]
Note that the order of the patterns in the regular expression matters.
let s = 'Please yes\nmake my day!'
s.match(/yes.*day/);
// Returns null
s.match(/yes[^]*day/);
// Returns ["yes\nmake my day"]
The sticky
flag indicates that the regular expression performs sticky matching in the target string by attempting to match starting at RegExp.prototype.lastIndex
.
let str = '#foo#'
let regex = /foo/y
regex.lastIndex = 1
regex.test(str) // true
regex.lastIndex = 5
regex.test(str) // false (lastIndex is taken into account with sticky flag)
regex.lastIndex // 0 (reset after match failure)
With the sticky flag y
, the next match has to happen at the lastIndex
position, while with the global flag g
, the match can happen at the lastIndex
position or later:
re = /\d/y;
while (r = re.exec("123 456")) console.log(r, "AND re.lastIndex", re.lastIndex);
// [ '1', index: 0, input: '123 456', groups: undefined ] AND re.lastIndex 1
// [ '2', index: 1, input: '123 456', groups: undefined ] AND re.lastIndex 2
// [ '3', index: 2, input: '123 456', groups: undefined ] AND re.lastIndex 3
// ... and no more match.
With the global flag g
, all 6 digits would be matched, not just 3.
As mentioned above, \w
or \W
only matches ASCII based characters; for example, a
to z
, A
to Z
, 0
to 9
, and _
.
To match characters from other languages such as Cyrillic or Hebrew, use \uhhhh
, where hhhh
is the character's Unicode value in hexadecimal.
This example demonstrates how one can separate out Unicode characters from a word.
let text = 'Образец text на русском языке'
let regex = /[\u0400-\u04FF]+/g
let match = regex.exec(text)
console.log(match[0]) // logs 'Образец'
console.log(regex.lastIndex) // logs '7'
let match2 = regex.exec(text)
console.log(match2[0]) // logs 'на' [did not log 'text']
console.log(regex.lastIndex) // logs '15'
// and so on
The Unicode property escapes feature introduces a solution, by allowing for a statement as simple as \p{scx=Cyrl}
. One can also use an external resource for getting the complete Unicode block range for different scripts, such as Regexp-Unicode-block.
let url = 'http://xxx.domain.com'
console.log(/[^.]+/.exec(url)[0].substr(7)) // logs 'xxx'
Instead of using regular expressions for parsing URLs, it is usually better to use the browsers built-in URL parser by using the URL API.
Specification |
---|
ECMAScript (ECMA-262) The definition of 'RegExp' in that specification. |
{{Compat("javascript.builtins.RegExp")}}