How to remove the brackets in a string? [duplicate]

0

With this code I search in a string the indexes of "[" and "]" and then delete what is inside them with a replace , but I also need remove the brackets , how should I do it? , because it does not eliminate them in my example ...

var a = "Hola[x]fsaaf fsa";

var b = a.indexOf("["); 
var c = a.indexOf("]"); 
var mostrar = a.substring(b, c +1);
var name = a.replace(new RegExp(mostrar, 'g'), "");

console.log(name);

Also try, something that I really know what it means, this:

var a = "Hola[x]fsaaf fsa";

var b = a.indexOf("["); // 6
var c = a.indexOf("]"); // 16
var mostrar = a.substring(b, c +1);
var name = a.replace(regex, "");
var  regex = new RegExp('\[?\b(?:' + mostrar + ')\b\]?', 'gi');
console.log(name);

But it leaves me the same string ...

    
asked by Eduardo Sebastian 28.06.2017 в 19:35
source

2 answers

1

Another more optimal solution, for the parser would be to do

var regExp = /\[[^\[\]]+\]/g
var mensaje = 'Hola[x] mundo[xasf234][a]'
var resultado = mensaje.match(regExp)
   
for(i in resultado) {
    resultado[i] = resultado[i].replace(/[\[\]]/g,'') //sanitiza el resultado
}

console.log(mensaje)
console.log(mensaje.replace(regExp,''))
console.log(resultado)
    
answered by 28.06.2017 / 19:55
source
1

I achieved it in two lines:

var a = "Hola[x]fsaaf fsa";

var b = a.indexOf("["); 
var c = a.indexOf("]"); 
var mostrar = a.substring(b, c +1);
var name = a.replace(new RegExp(mostrar, 'g'), "");
name = name.replace(/[\[\]']+/g,'');

console.log(name);

On a line:

var a = "Hola[x]fsaaf fsa";
var name = a.replace(/\[.*?\]/g, '')
console.log(name);

a = "Hola[x] mundo[xasf234][a]";
name = a.replace(/\[.*?\]/g, '')
console.log(name);
    
answered by 28.06.2017 в 19:43