简体   繁体   中英

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

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.

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
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM