A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/javascript/javascript-regexp-quantifier-5/ below:

JavaScript RegExp ^ Quantifier - GeeksforGeeks

JavaScript RegExp ^ Quantifier

Last Updated : 11 Jul, 2025

The ^ in JavaScript regular expressions is a special anchor that matches the beginning of a string or the start of a line when the multiline (m) flag is used. It is not a quantifier but an assertion used to control where matching starts in a string.

JavaScript
let regex = /^hello/;
let str1 = "hello world";
let str2 = "world hello";
console.log(regex.test(str1)); 
console.log(regex.test(str2)); 

The pattern /^hello/ matches strings starting with "hello". It does not match "hello" if it appears later in the string.

Syntax:
^pattern
Key Points Real-World Examples 1. Matching at the Start of a String JavaScript
let regex = /^abc/;
console.log(regex.test("abc123"));
console.log(regex.test("123abc"));

The pattern /^abc/ matches "abc" only if it appears at the start of the string.

2. Validating Input JavaScript
let regex = /^[A-Za-z0-9_]+$/;
console.log(regex.test("Valid123")); 
console.log(regex.test("123Valid"));  
console.log(regex.test("Invalid@")); 

Ensures the input starts with a valid alphanumeric or underscore character and contains only those characters.

3. Matching Specific Lines (Multiline Mode) JavaScript
let regex = /^hello/m;
let str = `hello world
world hello`;
console.log(str.match(regex));

Output
[
  'hello',
  index: 0,
  input: 'hello world\nworld hello',
  groups: undefined
]

In multiline mode, ^ matches "hello" only at the start of each line.

4. Validating Email Addresses JavaScript
let regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
console.log(regex.test("user@example.com"));
console.log(regex.test("invalid_email"));   

Ensures the email address starts with valid characters and follows the general format.

5. Detecting Special Cases JavaScript
let regex = /^#/;
let str = "# Comment line";
console.log(regex.test(str)); 

Matches strings starting with #, often used for parsing comments.

Common Patterns Using ^
/^hello/
/^\d+/
/^word/m
/^[a-zA-Z0-9]/
/^#/
Limitations Why Use the ^ Anchor? Conclusion

The ^ anchor is a powerful tool in regular expressions, enabling precise control over where matches occur in a string or across multiple lines.

Recommended Links:

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4