-3

I have a string of the following format:

[text text] Text to stay

And I want to remove the brackets and the text inside, so that the final string will be:

Text to Stay

Is it possible to achieve this using regex and the function replace?

pwolaq
  • 6,343
  • 19
  • 45
Elsendion
  • 187
  • 1
  • 4
  • 15
  • 1
    Probably more fitting duplicate: https://stackoverflow.com/questions/4292468/javascript-regex-remove-text-between-brackets – Kilian Stinson Jan 10 '17 at 14:37

4 Answers4

5

Yes, you can do it with replace function and regexp, as follow:

var text = "[text text] Text to stay";
var replaced = text.replace(/\[(.*)\]/, "");

Check this snippet:

var text = "[text text] Text to stay";
var replaced = text.replace(/\[(.*)\]/, "");

document.write(replaced);
Mateusz Woźniak
  • 1,479
  • 1
  • 9
  • 10
3

var str = "[text text] Text to stay";
alert(str.replace(str.substr(str.indexOf('['),str.indexOf(']') - str.indexOf('[') + 1),""));
2

You can try this short hand.

var text = "[text text] Text to stay";
var updatedText = text.split('] ')[1];
1

This regex also works when the text includes ].

var text = "[text text] Text to stay";
var replaced = text.replace(/\[.*?\] /, "");

document.write(replaced);
Huntro
  • 322
  • 1
  • 3
  • 16