Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 956
Moolla Avatar asked Nov 30 '25 08:11

Moolla


2 Answers

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.

like image 53
David Hedlund Avatar answered Dec 02 '25 20:12

David Hedlund


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
like image 40
dfsq Avatar answered Dec 02 '25 22:12

dfsq