Validate whether a text contains a substring in JavaScript or jQuery

2

I want to know how I can validate if an input parameter in a JavaScript function contains a substring. I have this:

function SweetAlert(Action) {
    if ($(Action:contains('Create')) == true) {
        swal('Buen trabajo!',
             'se creó el registro!',
             'success');
    } 
}
    
asked by Kmiilo Berrio Montoya 21.06.2016 в 15:52
source

2 answers

5

You can use indexOf that will return -1 if you can not find the string.

var cadena = "hola mundo";

console.log(
  cadena.indexOf("mundo") > -1
);

console.log(
  cadena.indexOf("no esta") > -1
);
    
answered by 21.06.2016 / 16:07
source
1

String.prototype.indexOf ()

As indexOf() returns -1 when you do not find,

~texto.indexOf(buscado)

will be 0 (and therefore falsy ) when buscado is not found within texto .

  

The operator ~ (bitwise not) reverses the value at the bit level.

     

As -1 is represented as 1111 1111 1111 1111 1111 1111 1111 1111 (in 32 bits),
~(-1) becomes 0 .


function contiene(texto, buscado) {
    return ~texto.indexOf(buscado)
}


String.prototype.includes () (ES6)

As of ECMAScript 6, includes() was added , which returns true or false (see compatibility ) .

texto.includes(buscado [, posicion])
    
answered by 13.02.2017 в 08:12