Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the forward slash mean within a JavaScript regular expression?

I can't find any definitive information on what / means in a JavaScript regex.

The code replace(/\r/g, '');

What I'm able to figure out is this:

  • / = I don't know
  • \r = carriage return
  • /g = I don't know but It may mean 'the match must occur at the point where the previous match ended.'
like image 834
Leoa Avatar asked Mar 27 '13 14:03

Leoa


People also ask

What is forward slash in regex JavaScript?

The forward slash character is used to denote the boundaries of the regular expression: ? The backslash character ( \ ) is the escaping character. It can be used to denote an escaped character, a string, literal, or one of the set of supported special characters.

What does slash means in regex?

Without any context such as a particular programming language's conventions, a forward slash in a regex has no special meaning; it simply matches a literal forward slash. In some languages, such as sed , Awk, Perl, and PHP, slashes are used around regular expressions in some contexts. /foo/n.

How do you handle forward slash in regex?

You can escape it by preceding it with a \ (making it \/ ), or you could use new RegExp('/') to avoid escaping the regex.

What does two forward slash mean in JavaScript?

Short answer: Those are just comments. Let them go. Long answer: In most of the programming languages, anything written after a // on the same line of code is treated as single line comments. There is also something called as multi-line comments.


1 Answers

The slashes indicate the start and end of the regular expression.

The g at the end is a flag and indicates it is a global search.

From the docs:

Regular expressions have four optional flags that allow for global and case insensitive searching. To indicate a global search, use the g flag. To indicate a case-insensitive search, use the i flag. To indicate a multi-line search, use the m flag. To perform a "sticky" search, that matches starting at the current position in the target string, use the y flag. These flags can be used separately or together in any order, and are included as part of the regular expression.

To include a flag with the regular expression, use this syntax:

 var re = /pattern/flags; 
like image 173
John Koerner Avatar answered Oct 08 '22 19:10

John Koerner