Summary: in this tutorial, you’ll learn about the JavaScript regular expressions. After the tutorial, you’ll know how to use regular expressions effectively to search and replace strings. Show
Introduction to regular expressions in JavaScriptA regular expression is a string that describes a pattern e.g., email addresses and phone numbers. In JavaScript, regular expressions are objects. JavaScript provides the built-in Regular expressions are useful for searching and replacing strings that match a pattern. They have many useful applications. For example, you can use regular expressions to extract useful information in web scraping like product prices. Or you can use regular expressions to validate form fields like email addresses and phone numbers. Creating a regular expressionTo create a regular expression in JavaScript, you enclose its pattern in forward-slash characters (
Note that a regular expression doesn’t have single quotes or double quotes like a regular string. Or you can use the
Both regular expressions are instances of the Testing for matchingThe The The following example use the
Using pattern flagsBesides a pattern, a 1) The ignore flag (i)The By default, searches are case-sensitive. For example
In this example, the The following example shows how to use the flag in the
2) The global flag (g)Another commonly used flag is the global flag ( When the It’s possible to combine flags e.g., The The The following example uses the
Output: How it works:
Searching stringsThe method To find all matches, you use the global flag ( The following example shows how to use the
Output:
Replacing stringsThe following example uses the
Output:
To replace all occurrences of
Output:
The following example uses both ignore and global flags to replace all occurrences of
Output:
Summary
Was this tutorial helpful ? Apa yang dimaksud dengan Regular Expression?Regular Expression (RE) adalah sebuah notasi yang dapat digunakan untuk mendeskripsikan pola dari kata yang ingin dicari. Sebagai contoh jika RE yang dibuat adalah ‹‹ nlp ›› maka kata yang akan cocok dengan pola ini hanya kata nlp (sama persis dengan yang ada pada RE).
Apa itu regex javascript?Regex adalah singkatan dari Regular Expresion. Regex merupakan sebuah teks (string) yang mendefinisikan sebuah pola pencarian sehingga dapat membantu kita untuk melakukan matching (pencocokan), locate (pencarian), dan manipulasi teks.
Metode untuk memeriksa apakah sebuah string lolos dari pola regular expression yang diinput adalah?Method test() digunakan untuk memeriksa apakah sebuah string lolos dari pola regular expression yang diinput. Jika lolos, hasilnya true. Jika tidak, hasilnya false.
|