user3142695
user3142695

Reputation: 17332

Remove square brackets at beginning and ending of string

I would like to remove square brackets from beginning and end of a string, if they are existing.

[Just a string]
Just a string
Just a string [comment]
[Just a string [comment]]

Should result in

Just a string
Just a string
Just a string [comment]
Just a string [comment]

I tried to build an regex, but I don't get it in a correct way, as it doesn't look for the position:

string.replace(/[\[\]]+/g,'')

Upvotes: 8

Views: 19207

Answers (3)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626794

Blue112 provided a solution to remove [ and ] from the beginning/end of a line (if both are present).

To remove [ and ] from start/end of a string (if both are present) you need

input.replace(/^\[([\s\S]*)]$/,'$1')

or

input.replace(/^\[([^]*)]$/,'$1')

In JS, to match any symbol including a newline, you either use [\s\S] (or [\w\W] or [\d\D]), or [^] that matches any non-nothing.

var s = "[word  \n[line]]";
console.log(s.replace(/^\[([\s\S]*)]$/, "$1"));

Upvotes: 3

epascarello
epascarello

Reputation: 207501

Probably a better reg exp to do it, but a basic one would be:

var strs = [
  "[Just a string]",
  "Just a string",
  "Just a string [comment]",
  "[Just a string [comment]]"
];

var re = /^\[(.+)\]$/;
strs.forEach( function (str) {
  var updated = str.replace(re,"$1");
  console.log(updated);
});

Reg Exp Visualizer

Upvotes: 0

blue112
blue112

Reputation: 56442

string.replace(/^\[(.+)\]$/,'$1')

should do the trick.

  • ^ matches the begining of the string
  • $ matches the end of the string.
  • (.+) matches everything in between, to report it back in the final string.

Upvotes: 10

Related Questions