-4

I am having trouble creating a regex that matches *|VALUE|*

I want to remove *| and |* but the regex i use only detects *|

str = *|VALUE|*
str.replace(/(^\*\||\|\*$)/, '') // VALUE|*

The OR operator does not seem to trigger.

Petros Kyriakou
  • 5,214
  • 4
  • 43
  • 82

3 Answers3

3

Your regex matches both cases. You don't need the capturing group ^\*\||\|\*$.

You could use replace:

var str = "*|VALUE|*";
str = str.replace(/^\*\||\|\*$/g, "");
console.log(str);

And indeed as @melpomene mentioned in the comment, you should use /g flag that performs a global search.

The fourth bird
  • 154,723
  • 16
  • 55
  • 70
2

(Referring to this question's original title) /^\*\|.*\|\*$/ matches a string that starts with *| and ends with |*.

So you can do this:

var str = '*|VALUE|*';
var trimmed = str.replace(/^\*\|(.*)\|\*$/, '$1');

console.log(trimmed);

Or use your original regex, but with a g (global) at the end. And don't forget the second argument to .replace:

var str = '*|VALUE|*';
var trimmed = str.replace(/(^\*\||\|\*$)/g, '');

console.log(trimmed);
JLRishe
  • 99,490
  • 19
  • 131
  • 169
0

Depending on what you want to do, you may want to capture each part of the regex separately and then use substitution inside of str.replace. (MDN). This can help you change a string such as *|VALUE|* to something like (VALUE) Firstly you should change the inside to .* which will simply match all characters between the two symbols you want.

let str = `*|VALUE|*`
let result = str.replace(/^(\*\|)(.*)(\|\*)$/, "($2)")
console.log(result)
Khauri
  • 3,753
  • 1
  • 11
  • 19