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"); 
5
  • 3
    When it's a regular expression. You can see from the docs that String.replace can take a regex as the first argument. Commented Jun 25, 2014 at 15:35
  • 2
    The expression /blue/ is a regular expression literal. Commented Jun 25, 2014 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. Commented Jun 25, 2014 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 stackoverflow.com/q/1144783/218196 Commented Jun 25, 2014 at 15:39
  • replace can do more things with regular expressions, you can replace patterns and also do global replaces, eg <code>"abcbabcba".replace(/b/g,"_") // == "a_c_a_c_a"</code> Commented Jun 25, 2014 at 15:40

2 Answers 2

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?

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

Comments

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")

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.