Remove square brackets at beginning and ending of string

12,811

Solution 1

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.

Solution 2

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"));

Share:
12,811
user3142695
Author by

user3142695

People who say nothing is impossible should try gargling with their mouths closed.

Updated on June 13, 2022

Comments

  • user3142695
    user3142695 almost 2 years

    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,'')
    
  • Cerbrus
    Cerbrus almost 8 years
    console.log("[just a [string]".replace(/^\[(.+)\]$/,'$1')); will return "just a [string"
  • blue112
    blue112 almost 8 years
    OP doesn't want to build a bracket matcher, just a regex that removes final and first bracket, if both are present. Please don't over-assume.
  • Cerbrus
    Cerbrus almost 8 years
    You're assuming "OP doesn't want to build a bracket matcher". We're both making assumptions, and I'm just pointing out a potential flaw.
  • Matt Burland
    Matt Burland almost 8 years
    @Cerbrus we only have what the OP gives us in way of definition for the problem. And in the comments on the question they have already stated that that input would have been invalid anyway.
  • Cerbrus
    Cerbrus almost 8 years
    Aren't reliable pieces of software supposed to be capable of dealing with invalid input? In other words: Shouldn't it check for invalid input?
  • user3142695
    user3142695 almost 8 years
    @blue112 You are right, I just need that simple thing.
  • Wiktor Stribiżew
    Wiktor Stribiżew almost 8 years
    Anyway, this won't match "[word\nline]" because . does not match everything.
  • Wiktor Stribiżew
    Wiktor Stribiżew almost 8 years
    It is identical to blue112's solution.
  • epascarello
    epascarello almost 8 years
    That is what happens when you go get coffee and than answer
  • Matt Burland
    Matt Burland almost 8 years
    @Cerbrus: yes, but those are two separate problems. Checking the validity and removing the outer brackets.