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

javascript regex

41179 просмотра

5 ответа

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.'
Автор: Leoa Источник Размещён: 12.11.2019 09:55

Ответы (5)


34 плюса

Решение

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;
Автор: John Koerner Размещён: 27.03.2013 03:00

9 плюса

To add a little more detail, the / characters are part of the regular expression literal syntax in JavaScript/ECMAScript. The / characters are used during lexical analysis to determine that a regular expression pattern is present between them and anything immediately following them will be regular expression flags. The ECMAScript standard has defined this in EBNF, for your perusual:

RegularExpressionLiteral :: / RegularExpressionBody / RegularExpressionFlags

A good analogy for the / in regular expressions is the " or ' that surround string literals in JavaScript.

Автор: Alex W Размещён: 20.08.2015 02:23

8 плюса

As others have pointed out, you should read the docs! That said:

Think of the forward slash as quotation marks for regular expressions. The slashes contain the expression but are not themselves part of the expression. (If you want to test for a forward slash, you have to escape it with a backwards slash.) The lowercase g specifies that this is a global search, i.e., find all matches rather than stopping at the first match.

Автор: Derek Henderson Размещён: 27.03.2013 03:01

6 плюса

As is indicated here, the forward slashes are not a part of the expression itself, but denote the beginning and ending of the expression.

Автор: metadept Размещён: 27.03.2013 02:58

2 плюса

To add to metadept's answer:

the g bit is the global indicator - see What does the regular expression /_/g mean? - i.e. replace all occurrences, not just the first one

Автор: Jane Размещён: 27.03.2013 03:01
Вопросы из категории :
32x32