-1

When running my replace statement using a regular expression not defined by the regex object it returns the correct result

var str = "from |cffa22fc8Peachee|r others";
var res = str.replace(/\|cffa22fc8Peachee\|r/gi, "red");
        
console.log(res);
//> from red others

However when it is executed using the regex object (which i need to be able to use) The result is different, even though i escaped the special characters.

var str = "from |cffa22fc8Peachee|r others";
var regex = new RegExp("/\|cffa22fc8Peachee\|r/", "gi");
var res = str.replace(regex, "red");

console.log(res)
//> from |red|r others
Amelia Magee
  • 452
  • 5
  • 14

2 Answers2

-2

My guess is that maybe this expression is what you wish to write:

\|[^|]*\|\S*

Test

const regex = /\|[^|]*\|\S*/g;
const str = `from |cffa22fc8Peachee|r others`;
const subst = `red`;

const result = str.replace(regex, subst);

console.log(result);

If you wish to explore/simplify/modify the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

Emma
  • 27,428
  • 11
  • 44
  • 69
-3

When creating a RegExp() you should omit the quotation marks, as they're already part of str. Instead of "/\|cffa22fc8Peachee\|r/", you're looking for /\|cffa22fc8Peachee\|r/:

var str = "from |cffa22fc8Peachee|r others";
var regex = new RegExp(/\|cffa22fc8Peachee\|r/, "gi");
var res = str.replace(regex, "red");

console.log(res)
Obsidian Age
  • 41,205
  • 10
  • 48
  • 71