-1

I am trying to replace the following in a Regex:-

[company-name]

Using Regex I would expect I could use was to use:-

str.replace(/[company-name]/g, 'Google');

But I know that the regex will replace any matching letter.

How am I able to replace the [company-name] with Google using JS Regex?

Thanks in advance for your help.

Web Nexus
  • 1,150
  • 9
  • 28
  • what is your example input string `str` value and what output of that string you wanna get? – Kamil Kiełczewski Jan 22 '19 at 12:05
  • Literal square brackets need to be escaped. See https://www.regular-expressions.info/characters.html#special – Phil Jan 22 '19 at 12:05
  • You need to escape the brackets with \ since they have a meaning in regexps. Though in this case using regexps seems overkill if it’s just a string replace. – Sami Kuhmonen Jan 22 '19 at 12:05
  • `[]` are meta characters. You need to escape them. `str.replace(/\[company-name\]/g, 'Google')` – adiga Jan 22 '19 at 12:06

4 Answers4

1

You need to escape the starting [ as well, in this case as they are special characters too:

var str = "I am from [company-name]!";
console.log(str.replace(/\[company-name]/gi, "Google"));

str = "[company-name]'s awesome!";
console.log(str.replace(/\[company-name]/gi, "Google"));
Phil
  • 157,677
  • 23
  • 242
  • 245
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
1

But I know that the regex will replace any matching letter.

This is only the case because you have encapsulated your characters in a character class by using [ and ]. In order to treat these as normal characters, you can escape these using \ in front of your special characters:

str.replace(/\[company-name\]/g, 'Google');

See working example below:

const str = "[company-name]",
res = str.replace(/\[company-name\]/g, 'Google');
console.log(res);
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
0

You should escape special characters like square brackets in this case. Just use:

str.replace(/\[company-name\]/g, 'Google');
lviggiani
  • 5,824
  • 12
  • 56
  • 89
Ernesto Stifano
  • 3,027
  • 1
  • 10
  • 20
0

you could do it this way :

var txt = "So I'm working at [company-name] and thinking about getting a higher salary."
var pattern = /\[.+\]/g;
console.log(txt.replace(pattern, "Google"))
Alexandre Elshobokshy
  • 10,720
  • 6
  • 27
  • 57