Bojan Radojevic
Bojan Radojevic

Reputation: 1015

How does '/' in javascript works?

How this is possible?

var re = /\w+/;

I have never seen something like this in any other language. Is this part of language sintax or something else? Leading '/' is what I don't understand, what exactly js does when it gets that with the "\w+/"?

Upvotes: 1

Views: 87

Answers (7)

sp00m
sp00m

Reputation: 48817

A bit of poetry: / is to regexps as " is to strings.

var intVar = 0;
var stringVar = "0";
var regexpVar = /0/;

Upvotes: 0

sparebytes
sparebytes

Reputation: 13096

Yes it's RegExp syntax that is part of the Javascript standard and is completely normal to use.

/\w+/ in RegExp means to look for alphanumeric characters in sequence... \w represents any letter or number in the alpha bet. + means that there should be at least 1 or more in a sequence.

"this123 is a test".match(/\w+/) == "this123"

Upvotes: 0

Daniel
Daniel

Reputation: 3806

That is a regular expression. It defines a rule for matching strings and numbers.

Upvotes: 0

epascarello
epascarello

Reputation: 207511

It is a regular expression literal.

From the MDN docs

You construct a regular expression in one of two ways:

Using a regular expression literal, as follows:

var re = /ab+c/; 

Regular expression literals provide compilation of the regular expression when the script is evaluated. When the regular expression will remain constant, use this for better performance.

Calling the constructor function of the RegExp object, as follows: 1

var re = new RegExp("ab+c");

Using the constructor function provides runtime compilation of the regular expression. Use the constructor function when you know the regular expression pattern will be changing, or you don't know the pattern and are getting it from another source, such as user input.

Upvotes: 3

MrSimpleMind
MrSimpleMind

Reputation: 8597

It isRegular expressions; which are used to perform pattern-matching and "search-and-replace" functions on text.

http://www.w3schools.com/jsref/jsref_obj_regexp.asp

Upvotes: 0

Denys Séguret
Denys Séguret

Reputation: 382150

This is a regular expression literal.

It's about the same as using the RegExp constructor to build your regular expression but it's immediately compiled when parsed and you don't need to escape \.

Note that you have the same syntactic structure in at least another language : Perl.

Upvotes: 1

PlantTheIdea
PlantTheIdea

Reputation: 16359

its not JavaScript-exclusive, its Regular Expressions, or RegEx. The '/' starts and ends the expression that you are comparing something against.

Upvotes: 0

Related Questions