2

I am running up against a weird problem here. When I run:

"#/a/b/c/d".replace("#\/","")

I get what I would expect: a/b/c/d.

But When I precede this regex with a start of string character ^, To get:

"#/a/b/c/d".replace("^#\/","")

This returns the original string "#a/b/c/d".

Could anybody explain why the hash isn't removed and possibly suggest an alternative that would remove the hash only if it appears at the beginning of the string?

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
user2662833
  • 1,005
  • 1
  • 10
  • 20

3 Answers3

1

The first argument to replace can be either a string or a regular expression.

You are passing a string, so it is looking for an exact match for that string.

Pass a regular expression instead.

"#/a/b/c/d".replace(/^#\//,"")
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

String.replace takes as its first argument either a string or a regexp. If you give it a string, it is not interpreted as or converted to a regexp; it is treated literally. Therefore, when you add ^ to your string, it replaces nothing, since there is no ^ in the input.

As explained in the comments, you can either pass a regexp literal (/.../) as the first argument, or you could construct a regexp with new RegExp (but why would you do that?).

0

When you pass a string as the first argument to .replace() method, the string is used as a literal and only 1 replacement can be made.

See the MDN replace reference:

substr (pattern)
A String that is to be replaced by newSubStr. It is treated as a verbatim string and is not interpreted as a regular expression.

What you need is to pass the regex object as the first argument:

"#/a/b/c/d".replace(/^#\//,"")
                    ^^^^^^

There is no point in using a constructor notation (RegExp("^#/") since the pattern is not built dynamically from variables.

There are no double slashes in the pattern! The outer /.../ are called regex delimiters. Then, what is insde is a pattern. The pattern is ^#/, but since the / are used as regex delimiters, the / in the pattern must be escaped to match a literal / (only in the regex literal notation).

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563