Remove the last word of a string jquery or javascript

1

Good morning I have the following text string in a variable

cad = "perro AND gato AND pajaro AND vaca AND"

Since the string is created automatically, it always adds the AND when concatenating a new element, but to show it, it must be without the last AND.

How can I remove the last AND from the string?

    
asked by Mauricio Delgado 16.11.2018 в 17:18
source

2 answers

1

If you know that the last thing in the string is AND, you can do the following:

var cad = cad.substring(cad.length-3)

You could also see how you are concatenating so that you do not add the last AND.

I hope it serves you.

    
answered by 16.11.2018 в 17:23
1

If you did not know the length of the last word:

var cad = "perro AND gato AND pajaro AND vaca ANDabcde...";

cad = cad.split(' ') // separa el string según espacios en blanco
         .slice(1, -1) // toma todos los elementos menos el último
         .join(' '); // vuelve a armar el string

console.log(cad);
    
answered by 16.11.2018 в 18:23