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.
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.
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.
(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);
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)