Diferentes formas de verificar si un string contiene otra cadena de texto en JavaScript – Different ways to check if a string contains a substring in JavaScript


You have this ways to find a string in another string (tenes las siguientes formas de encontrar una cadena de texto en otra):

-indexOf:

str.indexOf(searchValue[, fromIndex])

Parameters:

searchValue
value to search for.
fromIndex (Optional)
Index at which to start the searching forwards in the string.
Default is 0.
fromIndex <= 0 entire string is searched.
fromIndex >= str.length string is not searched and -1 is returned.
If searchValue is an empty string, str.length is returned.

Return value:
The index of the first occurrence of the specified value; -1 if not found.

                    
'Blue Whale'.indexOf('Blue');            // returns  0
'Blue Whale'.indexOf('Blute');           // returns -1
'Blue Whale'.indexOf('Whale',0);         // returns  5
'Blue Whale'.indexOf('Whale',5);         // returns  5
'Blue Whale'.indexOf('');                // returns  0
'Blue Whale'.indexOf('', 9);             // returns  9
'Blue Whale'.indexOf('', 10);            // returns 10
'Blue Whale'.indexOf('', 11);            // returns 10
                    

Browser compatibility:

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) (Yes) (Yes) (Yes) (Yes)

-includes:

str.includes(searchString[, position])

Parameters:

searchString
A string to be searched for within this string.
position (Optional)
The position within the string at which to begin searching for searchString.(defaults to 0).

Return value:
true if the given string is found anywhere within the search string; otherwise, false if not.

                    
var str = 'To be, or not to be, that is the question.';
console.log(str.includes('To be'));                 // true
console.log(str.includes('question'));              // true
console.log(str.includes('nonexistent'));           // false
console.log(str.includes('To be', 1));              // false
console.log(str.includes('TO BE'));                 // false
                    

Note you may need to load es6-shim or similar to get this working on older browsers.

require('es6-shim')

Browser compatibility:

Feature Chrome Firefox (Gecko) Internet Explorer Edge Opera Safari
Basic support 41 (40) No support Yes No support 9

-search:

str.search(regexp)

Parameters:

regexp
A regular expression object. If a non-RegExp object obj is passed, it is implicitly converted to a RegExp by using new RegExp(obj).

Return value:
The index of the first match between the regular expression and the given string; if not found, -1.

                    
var string = "foo", expr = "/oo/";
string.search(expr);
                    

Browser compatibility:

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) (Yes) (Yes) (Yes) (Yes)

-RegExp test:

regexObj.test(str)

Parameters:

str
The string against which to match the regular expression.

Return value:
true if there is a match between the regular expression and the specified string; otherwise, false.

                    
var string = "foo", expr = /oo/;    //no quotes
expr.test(string);
                    

Browser compatibility:

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) (Yes) (Yes) (Yes) (Yes)

-RegExp Match:

regexp[Symbol.match](str)

Parameters:

str
A String that is a target of the match.

Return value:
An Array containing the entire match result and any parentheses-captured matched results, or null if there were no matches.

                
                var string = "foo",
                        expr = "/oo/";
                string.match(expr);
                    

Browser compatibility:

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) (49) No support (Yes) (Yes)
Samples and definitions are from:
https://developer.mozilla.org/en-US/
Thanks Mozilla!

About the author:

Matías Creimerman

Matías Creimerman
I’m a specialist in design, development and management of software solutions with almost 20 years of experience. Microsoft Certificated Professional (MCP). Expert in dot net and Microsoft technologies. Experience and skills in designing solutions in a wide range of commercial, industrial and production areas. Design of architectures, software applications and processes. Skills in leadership and team management. Tech trainer. Technology researcher. Self-taught and dedicated to continuous learning. Skills in estimation, quotation, projects proposals and solutions design. Entrepreneurial spirit. Strong Tech profile but also customer oriented. I perform roles as fullstack dev, tech consultant, technical referent, development leader, team leader, architect, cross leader, tech manager, tech director, trainer, ramp-up & follow-up teams, software factory manager, DevOps and release manager. Regular chess player and musician.

Professional Website

In

Blogger

Github

About Me

Portfolio

Wordpress - Arquitectura y desarrollo de software

Wordpress - Personal Blog

Microsoft - Youracclaim Badges

Microsoft - Tech Profile

Microsoft - ASP.NET Forum

tw
Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License
Creative Commons License
This content is property of Matias Creimerman Any misuse of this material will be punishable
This work is licensed under a International Copyright Law protects “original works of authorship”
including photographs, videos, and blog posts posted on social media sites
The content has no rights to be shared without authorization or citation to the author.
This content cannot be sold be adapted or modified partially or totally.
All content shared outside this blog that doesn’t belong to the author must have citations to the author.

Responder

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión /  Cambiar )

Google photo

Estás comentando usando tu cuenta de Google. Cerrar sesión /  Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión /  Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión /  Cambiar )

Conectando a %s