Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

149
Views
¿Existe una forma breve de verificar si la entrada del usuario termina con uno de los elementos de una matriz?

¿Hay una forma breve de averiguar si la entrada del usuario termina con ( endsWith() ) uno de los elementos de una matriz? Me gustaría verificar si la entrada del usuario termina con uno de los siguientes sufijos: "ss", "ll", "tt". Si la entrada del usuario termina con uno de esos sufijos, el código debe alertar con un mensaje que dice "condición cumplida", de lo contrario, debe alertar "condición fallida". Puedo hacerlo usando declaraciones if simples como se muestra en el siguiente código:

 var inp = document.getElementById("inp"); function findingSuffixes(){ if(inp.value.endsWith('ss') || inp.value.endsWith('tt') || inp.value.endsWith('ll')){ alert('condition met') } else { alert('condition failed') } }
 <p>Enter a word:</p> <input type="text" id="inp"> <button onclick="findingSuffixes()">Find out</button>

Pero esto es un poco tortuoso.

Traté de abordarlo desde un ángulo diferente. Creé una matriz y almacené los sufijos en ella y luego recorrí esa matriz y pasé la matriz[i] al método endsWith como argumento, pero no funcionó como se esperaba.

 var inp = document.getElementById("inp"); suffixes = ["ss", "tt", "ll"]; function findingSuffixes(){ for(var i=0; i < suffixes.length; i++){ if(inp.value.endsWith(suffixes[i])){ alert("condition Met") } else { alert("condition failed") } } }
 <p>Enter a word:</p> <input type="text" id="inp"> <button onclick="findingSuffixes()">Find out</button>


TL'DR: ¿Hay una forma breve de verificar si la entrada del usuario termina con uno de los elementos en una matriz?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

El problema con su código es que emite la alert mientras aún está en el bucle. Solo desea que declare "cumplido" o "fallido" cuando lo sepa con certeza. Ajusté el código para mostrar cómo se puede hacer esto. Uso break para salir del bucle una vez que cumplimos la condición, ya que no hay necesidad de buscar más.

 var inp = document.getElementById("inp"); var suffixes = ["ss", "tt", "ll"]; function findingSuffixes(){ var msg = "condition failed"; for(const suffix of suffixes){ if (inp.value.endsWith(suffix)){ msg = "condition Met"; break; // no need to continue in the loop } } alert(msg); }
 <p>Enter a word:</p> <input type="text" id="inp"> <button onclick="findingSuffixes()">Find out</button>

about 4 years ago · Juan Pablo Isaza Report

0

Podría tomar una expresión regular y probar la cadena contra esta expresión.

 /(ll|ss|tt)$/ ( ) a group ll|ss|tt alternatives with ll ss or tt $ followd by an end of string 

 function findingSuffixes() { if (/(ll|ss|tt)$/.test(inp.value)) { console.log('condition met'); } else { console.log('condition failed'); } } const inp = document.getElementById("inp");
 <p>Enter a word:</p> <input type="text" id="inp"> <button onclick="findingSuffixes()">Find out</button>

about 4 years ago · Juan Pablo Isaza Report

0

Como @Barmar menciona que es mejor usar .some()

 var inp = document.getElementById("inp"), sfs = ["ss", "tt", "ll"]; function findingSuffixes() { alert(sfs.some(sf => inp.value.endsWith(sf)) ? "Condition met" : "Condition failed"); }
 <p>Enter a word:</p> <input type="text" id="inp"> <button onclick="findingSuffixes()">Find out</button>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!