What does the forward slash mean within a JavaScript regular expression?
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.'
Ответы (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.
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:016 плюса
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:582 плюса
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Вопросы из категории :
- javascript Как определить, какой из указанных шрифтов был использован на веб-странице?
- javascript Валидация клиентской стороны ASP.Net
- javascript Длина объекта JavaScript
- javascript Получение текста из выпадающего списка
- javascript Скрипт входа со скрытыми кнопками
- javascript Как автоматически изменить размер текстовой области с помощью Prototype?
- javascript Удаление элементов с помощью Array.map в JavaScript
- javascript Прокрутка переполненных DIV с помощью JavaScript
- javascript API Карт Google - проблемы с классом GLatLngBounds
- javascript Проверка десятичных чисел в JavaScript - IsNumeric ()
- regex Learning Regular Expressions
- regex Regex и unicode
- regex Мое регулярное выражение слишком подходит. Как мне это остановить?
- regex Как выполнить подстановку Perl для строки, сохранив оригинал?
- regex Замена n-го экземпляра совпадения с регулярным выражением в Javascript
- regex Как заменить простые URL ссылками?
- regex Python re.sub с флагом не заменяет все вхождения
- regex Как проверить адрес электронной почты в JavaScript
- regex Как экранировать текст для регулярного выражения в Java
- regex Регулярное выражение, которое будет соответствовать объявлению метода Java