0

I came across a bit of code that looks something like this:

var str="I like blue";
str.replace(/blue/,"red");

What is happening here? When are string literals not required to be enclosed in quotes? What is the benefit of this approach as opposed to

str.replace("blue","red"); 
gloo
  • 2,490
  • 3
  • 22
  • 38
  • 3
    When it's a regular expression. [You can see from the docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace) that `String.replace` can take a regex as the first argument. – Andy Jun 25 '14 at 15:35
  • 2
    The expression `/blue/` is a [regular expression literal](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions). – Pointy Jun 25 '14 at 15:36
  • 1
    `/blue/` is not a string literal, it's a regular expression literal. `.replace` can search for either a string or a regex. – gen_Eric Jun 25 '14 at 15:36
  • *"When are string literals not required to be enclosed in quotes?"* Never. *"What is the benefit of this approach as opposed to"* There is none in your example, but see http://stackoverflow.com/q/1144783/218196 – Felix Kling Jun 25 '14 at 15:39
  • replace can do more things with regular expressions, you can replace patterns and also do global replaces, eg "abcbabcba".replace(/b/g,"_") // == "a_c_a_c_a" – imma Jun 25 '14 at 15:40

2 Answers2

1

In Javascript, a literal enclosed within / characters is not a String, is a RegExp (regular expression)

So /blue/ is equivalent to new RegExp("blue")

Pablo Lozano
  • 10,122
  • 2
  • 38
  • 59
1

When are string literals not required to be enclosed in quotes?

Never:

StringLiteral ::
    " DoubleStringCharacters_opt "
    ' SingleStringCharacters_opt '

(Note: template literals in ES6 are not string literals either.)

What is the benefit of this approach as opposed to [...]

There is none in your example, but if you want to replace all occurrences of a string, you have to use a regular expression with the global modifier: How to replace all occurrences of a string in JavaScript?

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143