I want to remove the following characters: [
, ]
, "
, \
if any are at the beginning or end of a string, but not if they are in the middle.
So, if the string is ""\[\]][hello" world "\[\"]]
, I'd like it to become, hello" world
I can't figure out how to do it. I've tried these and many others and none seems to work:
string.replace(/^[\[ |\] |\" |\\ ]$,"")
string.replace(/^[\[ \] \" \\ ]$/,"")
Any help would be much appreciated.
CodePudding user response:
You're close. You need two alternatives, one for the beginning and another for the end. Each should then be a character set in []
listing all the characters you want to remove.
You also need the g
modifier to replace twice in the same string.
let string = '""\[\]][hello" world "\[\"]]';
console.log(string.replace(/^["\[\]\\] |["\[\]\\] $/g, ''));
CodePudding user response:
I split the problem into following subproblems:
- Find these characters at the start of a string
- Find these characters at the end of a string
I came up with following regex-patterns to solve these:
- /(^["\[]] )/g
- /["\[]] $/g
When working with regex, I recommend following site: regexr.com/6d193