Remove substring with regex

1

I have the string:

var str = "Quantidade [12]";

I need to retrieve the string but remove the space and [12], ie I need to return only the value: Quantity .

In case the string is var str = "Quantidade máxima [12]"; , I need to get all the text to the left of the bracket, that is, the value Max amount .

Both the size of the strings and the value between the brackets can change, the mask would be basically:

var str = "string [*]";

I will always have only this pair of brackets and a numeric value inside. How can I recover the entire string by removing space and numeric value?

    
asked by anonymous 02.10.2015 / 22:46

2 answers

1

If the pattern you have is string + + [*] it seems to me that .split() arrives.

You can do this without needing RegExp:

var str = "Quantidade [12]";
var texto = str.split(' ')[0];

If you really want to use regex, it would suffice /(\w+)/ , ie:

var str = "Quantidade [12]";
var texto = str.match(/(\w+)/)[0];
    
02.10.2015 / 23:22
1

Using regular expressions

The last spaces end up staying. The trim () function removes spaces at the end.

var regexp = new RegExp(/^[A-Za-z ]+/);
regexp.exec("Quantidade máxima [12]").trim(); // "Quantidade máxima"

Manipulating with substring

To include the above example "Maximum Quantity", you can manipulate the string directly:

var valor = "Quantidade máxima [12]"; 
var resultado = val.substring(0, val.indexOf("[") - 1); // "Quantidade máxima"
    
02.10.2015 / 23:07