1

In the pursuit of understanding JavaScript/OOP better, I'm curious how regular expression argument parameters are handled in JavaScript. I already understand a lot about regular expressions, so this isn't about interpreting patterns. This is about identifying how JavaScript handles it.

Example:

newStr = str.replace(/(^\W*|\W*$)/gi,'');

This basically trims any special characters and white-space from a string. However, /(^\W*|\W*$)/gi is not an encapsulated string, therefore, it baffles me to understand this concept since the JS object is not a string, nor a number. Is this object-type alone (i.e., regex-only), or does it serve other purposes?

1
  • Thanks everyone for your quick responses! All of your answers are good! Commented Nov 6, 2012 at 15:52

5 Answers 5

6

It's just a special syntax that JavaScript has for regular expressions. It evaluates to an object, and is no different than:

var rex = /(^\W*|\W*$)/gi;
decision = str.replace(rex, '');

Or:

var rex = new RegExp('^\\W*|\\W*$', 'gi');

The RegExp MDN documentation has plenty of detailed info.

Sign up to request clarification or add additional context in comments.

Comments

3

Regexes are first-class citizens in JavaScript, i. e. they are a separate object type.

You can construct a new RegExp object using its standard constructor:

var regex = new RegExp("(^\\W*|\\W*$)", "gi");

or using the special "regex literal" notation that allows you to cut down on backslashes:

var regex = /(^\W*|\W*$)/gi;

Comments

2

/(^\W*|\W*$)/gi is a regular expression literal, which is an object type in JavaScript. This type can be passed as the first parameter to the replace method, which accepts either a regex or a substring.

Comments

2

Is this object-type alone (i.e., regex-only)

This is correct. RegExp objects are a special type of value that's built-in to the language. They are one of only a handful of types that have "literal" representations in JavaScript.

This does make them fairly unique; there aren't any other special-purpose literals in the language. The other literals are generic types like:

  • null
  • boolean values (true/false)
  • numbers (1.0, 2e3, -5)
  • strings ('hello', "goodbye")
  • Arrays ([1, 2, 3])
  • Objects ({ name: "Bob", age: 18 })

Comments

1

To add to the people saying largely the same thing:

On top of the fact that it's a literal with its own syntax, you can actually access its methods in literal form:

/bob/gi.exec(" My name is Bob ");

...so long as the browser you're using is young enough to indeed support RegEx literals (it's pretty hard to find one that doesn't, these days, and if you do, does the browser support CSS?).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.