Delete text inside brackets in javascript


I have the following simple code:

<input id="nick" type="text"/>

var c = document.getElementById('nick').value


I need to remove a part of the name, only if it has brackets [] . So if you have this name: 'Hola soy juan [soy pro]' , it would look like this: 'Hola soy juan' .

asked by Eduardo Sebastian 27.04.2017 в 00:55

3 answers


An alternative is the use of replace in conjunction with the regular expression 1 /\[.+?]/g where:

  • \[ : escape the opening bracket.
  • . : Any character
  • + : One or more characters equal to the previous one
  • ? : Stingy, the least number of times
  • g : Global

1 By regular expression I am referring to a RegEx object. Just as the Array objects when declared using the short form, [elemento1,elmento2] , do not carry quotes, nor do the RegEx /expresionregular/banderas objects carry it.

In the following code, two cases are included, one similar to that indicated by the OP and another a bit more complex.

//Caso simple, una sóla ocurrencia
var texto1 = "Conservar este texto [eliminar este] pero convervar esto otro";

//Caso complejo, varias ocurrencias no consecutivas
var texto2 = "manzana [melón] melocotón [membrillo] mora";

// Asignar la expresión regular propuesta a una variable
var re = /\[.+?]/g;

//Realizar la eliminación mediante reemplazar para los dos casos.
var salida1 = texto1.replace(re,'');
var salida2 = texto2.replace(re,'');

//Agregar el resultado a la página
document.write('Caso 1: ' + salida1 + '<br/>Caso 2: ' + salida2);
answered by 27.04.2017 / 04:50

You can use substr and replace in a loop to delete all texts that are within [ ]

For example, if you try 'Javier [the best] of [your home in] Panama' , the result will be Javier de Panama

Then we eliminate all repeated spaces with the code

output.replace(/\s+/g,' ').trim();

I hope you serve

var example = document.getElementById('example'),
     result = document.getElementById('result');

  example.addEventListener('keyup',function() {
    var output = this.value,
        finish = false;
    while(!finish) {
      if(output.indexOf('[') >=0 && output.indexOf(']') >= 0) {
        output = output.replace(output.substr(output.indexOf('['), output.indexOf(']')  - output.indexOf('[') + 1),'');
      else {
        finish = true;

    result.innerText = output.replace(/\s+/g,' ').trim();
<input type="text" id="example" />
<span id="result"></span>
answered by 27.04.2017 в 07:22

I've already done it if someone is interested:

var c = "Hola amigos [quiero que me eliminen]";
var d = c.split('');
var buscar1 = d.indexOf('[');
buscar1 = parseInt(buscar1);
var buscar2 = d.indexOf(']');
buscar2 = parseInt(buscar2);
var total = buscar2 - buscar1;
var eliminar = d.splice(buscar1, (total +1));
var g = d.join('');

answered by 27.04.2017 в 03:19