¿Cómo comprobar que una string comienza/termina con una string específica en jQuery?

JavaScript proporciona muchos métodos de string que verifican si una string es una substring de otra string. Entonces, jQuery no sería necesario en absoluto para realizar esta tarea. Sin embargo, cubriremos todas las diferentes formas de verificar si una string comienza o termina con una string: 

Consideremos una string str = «Bienvenido a GEEKS PARA GEEKS!!!». Ahora tenemos que encontrar si la string str comienza con startword = «Bienvenido» y termina con endword = «!!!».

Enfoques:  
método beginWith() y EndsWith() : Comprueba si una string comienza o termina con la substring específica.

Ejemplo:  

Javascript

if (str.startsWith(startword) && str.endsWith(endword)) {
 
    // case sensitive
    console.log("Yes, The string " + str + " starts with "
            + startword + " and ends with " + endword);
}

método search(): Comprueba si una string en particular está contenida en otra string y devuelve el índice inicial de esa substring.

Ejemplo:  

Javascript

if (str.search(startword)==0 &&
    str.search(endword)==stringlength-endwordlength ) {
 
    // case sensitive
    console.log("Yes, The string " + str + " starts with "
            + startword + " and ends with " + endword);
}

Método indexOf(): como sugiere el nombre, encuentra el índice inicial de una substring en la string.

Ejemplo: 

Javascript

if (str.indexOf(startword)==0 &&
    str.indexOf(endword)==stringlength-endwordlength) {
             
    console.log("Yes, The string " + str + " starts with "
            + startword + " and ends with " + endword);
}

Método substring(): Devuelve una string presente entre el índice de inicio y final.

Ejemplo:  

Javascript

if(str.substring(0, startwordlength)==startword
        && str.substring(stringlength-endwordlength,
        stringlength)==endword) {
         
    console.log("Yes, The string " + str + " starts with "
            + startword + " and ends with " + endword);
}

Método substr(): Es similar al método substring() pero toma el índice de inicio y la longitud de la substring como parámetros.

Ejemplo: 

Javascript

if(str.substr(0, startwordlength)==startword
        && str.substr(stringlength-endwordlength,
        endwordlength)==endword) {
 
    console.log("Yes, The string " + str + " starts with "
            + startword + " and ends with " + endword);
}

Método slice(): este método devuelve los segmentos de string entre dos índices en una string.

Ejemplo:  

Javascript

if(str.slice(0, startwordlength)==startword
        && str.slice(stringlength-endwordlength,
        stringlength)==endword) {
 
    console.log("Yes, The string " + str + " starts with "
            + startword + " and ends with " + endword);
}

Tomemos un ejemplo de texto en el elemento h1 y verifiquemos si comienza y termina con la substring dada. 

Javascript

<!DOCTYPE html>
<html>
 
<head>
    <title>
        How to know that a string starts/ends
        with a specific string in jQuery?
    </title>
 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
    </script>
</head>
 
<body>
    <h1 id="text">
        Welcome To GEEKS FOR GEEKS!!!
    </h1>
 
    <h2>
        Check whether a word is present
        in the above sentence
    </h2>
 
    <input type="text" id="startkey">
    <input type="text" id="endkey">
    <button onclick="MyFunction()"> Check </button>
 
    <h2> startsWith() and endsWith() method </h2>
    <h2 id="startswith"> </h2>
 
    <h2> indexOf() method </h2>
    <h2 id="indexOf"></h2>
 
    <h2> search() method </h2>
    <h2 id="search"></h2>
 
    <h2> substring() method </h2>
    <h2 id="substring"></h2>
 
    <h2> substr() method </h2>
    <h2 id="substr"> </h2>
 
    <h2> slice() method </h2>
    <h2 id="slice"></h2>
 
 
    <script>
        var str = document.getElementById("text").innerText;
        stringlength = str.length;
        var startword = "";
        var endword = "";
        function MyFunction() {
            startword = document.getElementById("startkey").value;
            endword = document.getElementById("endkey").value;
            console.log(startword);
            console.log(endword)
            startwordlength = startword.length;
            endwordlength = endword.length;
 
            if (str.startsWith(startword) && str.endsWith(endword)) {
                // case sensitive
                var h2 = document.getElementById("startswith");
                h2.innerHTML =
                    "Yes, The string " + str + " starts with "
                    + startword + " and ends with " + endword;
            }
            else {
                var h2 = document.getElementById("startswith");
                h2.innerHTML =
                    "No, The string " + str +
                    " doesn't start and endwith the given words";
            }
            //Js
            if (str.indexOf(startword) == 0 && str.indexOf(
                endword) == stringlength - endwordlength) {
                var h2 = document.getElementById("indexOf");
                h2.innerHTML =
                    "Yes, The string " + str + " starts with "
                    + startword + " and ends with " + endword;
            }
            else {
                var h2 = document.getElementById("indexOf");
                h2.innerHTML =
                    "No, The string " + str +
                    " doesn't start and endwith the given words";
            }
            //Js
            if (str.search(
                startword) == 0 && str.search(endword)
                    == stringlength - endwordlength) {
 
                // case sensitive
                var h2 = document.getElementById("search");
                h2.innerHTML = "Yes, The string " + str +
                        " starts with " + startword +
                        " and ends with " + endword;
            }
            else {
                var h2 = document.getElementById("search");
                h2.innerHTML = "No, The string " + str +
                    " doesn't start and endwith the given words";
            }
            //Js
            if (str.substring(
                0, startwordlength) == startword && str.substring(
                    stringlength - endwordlength, stringlength) == endword) {
                var h2 = document.getElementById("substring");
                h2.innerHTML =
                    "Yes, The string " + str + " starts with "
                    + startword + " and ends with " + endword;
            }
            else {
                var h2 = document.getElementById("substring");
                h2.innerHTML =
                    "No, The string " + str +
                    " doesn't start and endwith the given words";
            }
 
            if (str.substr(
                0, startwordlength) == startword && str.substr(
                    stringlength - endwordlength, endwordlength) == endword) {
                var h2 = document.getElementById("substr");
                h2.innerHTML =
                    "Yes, The string " + str + " starts with "
                    + startword + " and ends with " + endword;
            }
            else {
                var h2 = document.getElementById("substr");
                h2.innerHTML =
                    "No, The string " + str +
                    " doesn't start and endwith the given words";
            }
            if (str.slice(
                0, startwordlength) == startword && str.slice(
                    stringlength - endwordlength, stringlength) == endword) {
                var h2 = document.getElementById("slice");
                h2.innerHTML =
                    "Yes, The string " + str + " starts with " +
                    startword + " and ends with " + endword;
            }
            else {
                var h2 = document.getElementById("slice");
                h2.innerHTML =
                    "No, The string " + str +
                    " doesn't start and endwith the given words";
            }
        }
    </script>
</body>
 
</html>

Producción: 


Publicación traducida automáticamente

Artículo escrito por sathiyajith19 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *