Moolla
Moolla

Reputation: 169

How can I remove text in brackets in a string without using regex in Javascript?

How can I remove anything inside angle brackets in a string without using regex?

For example is I have the following input:

var str = "This <is> some <random> text";  

and would like to obtain the following output:
This some text

Upvotes: 2

Views: 462

Answers (3)

Andras Toth
Andras Toth

Reputation: 628

var str = "This (is) some (random) text";

while (str.indexOf('(') != -1) {
    str = str.substring(0, str.indexOf('(') - 1) + str.substring(str.indexOf(')') + 1);
}
// Output: This some text

Upvotes: 1

David Hedlund
David Hedlund

Reputation: 129832

Making the assumption that the brackets will line up as in your example, you could do something like this:

str = str.split('(')
   .map(function(s) { return s.substring(s.indexOf(')')+1); })
   .join('');

Note that, when removing the text within brackets, you are left with double spaces. This seems to match your request since both spaces are in fact outside of your brackets. They could be removed with .replace(/\s+/g, ' '), but that would of course be using regex. If you want to assume that a word within brackets is always followed by a space that is also to be removed, you could do something like this:

str = str.split('(')
   .map(function(s) { 
      return s.indexOf(') ') == -1 
         ? s
         : s.substring(s.indexOf(') ') + 2);
    })
   .join('');

In this example you need to check for the case where there is no bracket in the string ("This "). We didn't need that before, since we always just did +1, and if indexOf yielded -1, that would simply mean taking the entire string.

Upvotes: 7

dfsq
dfsq

Reputation: 193301

What a strange requirement! This will not use regexp:

"This (is) some (random) text".split('(').map(function(el) {
    var i = el.indexOf(')');
    return el = ~i ? el.substr(i) : el;
}).join('('); // This () some () text

Upvotes: 2

Related Questions