1

I'm looking through the source code to base.js, within it there is a object referenced via what seems like a regex?

if (ancestor && (typeof value == "function") && // overriding a method?

    // the valueOf() comparison is to avoid circular references
    (!ancestor.valueOf || ancestor.valueOf() != value.valueOf()) && 
    /\bbase\b/.test(value)) {

It's that "/\bbase\b/" object.

What is this? My search engine in my ide treats it as a regex? A google search renders no results.

  • 2
    yes, it is a regex. \b means word boundary, like a space. – Brian Glaz Jan 12 '14 at 00:10
  • See [What is a word boundary in regexes?](http://stackoverflow.com/questions/1324676/what-is-a-word-boundary-in-regexes) for further info. – Alex Jan 12 '14 at 00:12
  • How would a JavaScript interpreter use this?/ how does it work? – Nathaniel Bennett Jan 12 '14 at 00:13
  • The accepted answer to the aforementioned question does a pretty good job of explaining how a word boundary works. As far as "how does a JavaScript interpreter use this?" I'm not sure I understand what you're asking. – Alex Jan 12 '14 at 00:15
  • No, I was just confused, as the code uses the regular expression as an object reference. What happens if there are multiple objects that fit regular expression? would it just perform the task on all objects? Also does this act more like a macro? I imagine JavaScript would have to resolve the expression before executing any code. – Nathaniel Bennett Jan 12 '14 at 00:19
  • @NathanielBennett "the code uses the regular expression as an object reference" - yes, the regex literal syntax returns a [RegExp](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) object (similarly to how `{}` returns a plain object). I didn't understand the rest of your comment. – Fabrício Matté Jan 12 '14 at 00:27
  • And no, regex literals will instantiate regex objects at runtime (that is, if the condition fails before reaching the regex literal, it won't instantiate a regex object), similarly to string/object/array literals' behavior. – Fabrício Matté Jan 12 '14 at 00:31
  • I see... no I was wrong, the .test() call is inside a RegExp object, sorry, my mistake. Hahaha, I thought something completely different. Thank you. – Nathaniel Bennett Jan 12 '14 at 00:36

1 Answers1

1

Yes, in JavaScript, /.../ delimits a regular expression literal. The characters inside the literal are the pattern itself. It's roughly equivalent to:

new RegExp("\\bbase\\b").test(value)

Notice that in the string literal ("...") above, the \ characters need to be escaped, but in the regex literal they didn't. This makes writing regular expression patterns much more natural using literals, and it's one of the reasons regex literals were included in the language.

The \b matches any word boundary a point where the previous character is a word character and the next is not or vice-versa.

p.s.w.g
  • 146,324
  • 30
  • 291
  • 331