Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Js Regexp in JavaScript

Js Regexp in JavaScript

? JavaScript RegExp (Regular Expressions)

A RegExp (Regular Expression) is a pattern used to match character combinations in strings. It's super useful for searching, validating, and manipulating text.


Creating a RegExp

1. Using literal syntax:

const regex = /hello/i;  // 'i' for case-insensitive

2. Using constructor:

const regex = new RegExp('hello', 'i');

Common Methods with RegExp

Given:

const str = "Hello World!";const regex = /hello/i;
  • test() — tests if pattern exists, returns true or false:

regex.test(str);  // true
  • exec() — returns details about the match or null:

const result = regex.exec(str);console.log(result);// Output example:// ["Hello", index: 0, input: "Hello World!", groups: undefined]
  • String.match() — gets all matches (returns array or null):

const matches = str.match(/o/g);  // ['o', 'o']
  • String.replace() — replaces matched parts:

const newStr = str.replace(/world/i, "JS");console.log(newStr);  // "Hello JS!"

RegExp Flags

FlagMeaning
gGlobal search (all matches)
iCase-insensitive search
mMulti-line search
uUnicode support
sDot matches newline
ySticky search

Example: Validate Email Format

const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$/i;console.log(emailRegex.test("test@example.com"));  // trueconsole.log(emailRegex.test("invalid-email"));     // false

Example: Extract Numbers from String

const str = "My phone number is 123-456-7890.";const numbers = str.match(/\d+/g);console.log(numbers);  // ["123", "456", "7890"]

Summary

  • RegExp helps find patterns in strings.

  • Use test(), exec(), match(), replace() for common tasks.

  • Use flags for behavior control.


Want me to help you build a specific regex or explain regex syntax like quantifiers, groups, or character classes?

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql