Remove substring with regex

Asked

Viewed 672 times

1

I got the string:

var str = "Quantidade [12]";

I need to recover the string but remove the space and the [12], IE, I need to return only the value: Amount.

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

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 only have this pair of brackets and a numerical value inside. How can I recover the entire string by removing the space and the numerical value?

2 answers

1

Using regular expressions

The last spaces end up remaining. The function Trim() removes the 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 example quoted "Maximum amount", you can manipulate the string directly:

var valor = "Quantidade máxima [12]"; 
var resultado = val.substring(0, val.indexOf("[") - 1); // "Quantidade máxima"
  • But when you have something like "Maximum quantity [12]", I need to return "Maximum quantity" without the brackets, number and last space.

  • this information is there, I inform that the size of the strings can change and even suggest what would be a mask.

1

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

You can do it like this without needing Regexp:

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

If you really want to use regex, that would be enough /(\w+)/, that is to say:

var str = "Quantidade [12]";
var texto = str.match(/(\w+)/)[0];

Browser other questions tagged

You are not signed in. Login or sign up in order to post.