Contiene mayúsculas y minúsculas


Tengo lo siguiente:

if (referrer.indexOf("Ral") == -1) { ... }

Lo que me gusta hacer es hacer Ral insensible a mayúsculas y minúsculas, para que pueda ser RAl, rAl, etc. y aún coinciden.

¿Hay alguna manera de decir que Ral tiene que ser insensible a mayúsculas y minúsculas?

Author: Alexander Abakumov, 2012-01-25

9 answers

Añádase .toLowerCase() después de referrer. Este método convierte la cadena en una cadena minúscula. Luego, use .indexOf() usando ral en lugar de Ral.

if (referrer.toLowerCase().indexOf("ral") === -1) { 

Lo mismo también se puede lograr usando una Expresión Regular (especialmente útil cuando se desea probar con patrones dinámicos):

if (!/Ral/i.test(referrer)) {
   //    ^i = Ignore case flag for RegExp
 470
Author: Rob W,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-24 20:38:55

Otra opción es usar el método de búsqueda de la siguiente manera:

if (referrer.search(new RegExp("Ral", "i")) == -1) { ...

Se ve más elegante que convertir toda la cadena a minúsculas y puede ser más eficiente.
Con toLowerCase() el código tiene dos pasadas sobre la cadena, una pasada es sobre toda la cadena para convertirla a minúsculas y otra es buscar el índice deseado.
Con RegExp el código tiene un paso sobre la cadena que parece coincidir con el índice deseado.

Por lo tanto, en cadenas largas recomiendo use la versión RegExp (supongo que en cadenas cortas esta eficiencia se debe a la creación del objeto RegExp)

 75
Author: Kfir Erez,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-18 16:01:55

Use una expresión regular:

if (!/ral/i.test(referrer)) {
    ...
}

O, use .toLowerCase():

if (referrer.toLowerCase().indexOf("ral") == -1)
 19
Author: gilly3,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-24 20:40:08

Hay un par de enfoques aquí.

Si desea realizar una comprobación que no distingue mayúsculas de minúsculas solo para esta instancia, haga algo como lo siguiente.

if (referrer.toLowerCase().indexOf("Ral".toLowerCase()) == -1) {
    ...

Alternativamente, si está realizando esta comprobación regularmente, puede agregar un nuevo método similar a indexOf() a String, pero haga que sea insensible a mayúsculas y minúsculas.

String.prototype.indexOfInsensitive = function (s, b) {
    return this.toLowerCase().indexOf(s.toLowerCase(), b);
}

// Then invoke it
if (referrer.indexOfInsensitive("Ral") == -1) { ...
 10
Author: cheeken,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-24 20:47:34
if (referrer.toUpperCase().indexOf("RAL") == -1) { ...
 4
Author: Kendall Frey,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-24 20:39:50

Para hacer una mejor búsqueda utilice el siguiente código,

var myFav   = "javascript";
var theList = "VB.NET, C#, PHP, Python, JavaScript, and Ruby";

// Check for matches with the plain vanilla indexOf() method:
alert( theList.indexOf( myFav ) );

// Now check for matches in lower-cased strings:
alert( theList.toLowerCase().indexOf( myFav.toLowerCase() ) );

En la primera alert(), JavaScript devolvió "-1" - en otras palabras, indexOf() no encontró una coincidencia: esto es simplemente porque "JavaScript" está en minúsculas en la primera cadena, y correctamente mayúscula en la segunda. Para realizar búsquedas que no distinguen mayúsculas de minúsculas con indexOf (), puede hacer ambas cadenas en mayúsculas o minúsculas. Esto significa que, como en la segunda alert (), JavaScript solo comprobará la ocurrencia de la cadena que están buscando, mayúsculas ignoradas.

Referencia, http://freewebdesigntutorials.com/javaScriptTutorials/jsStringObject/indexOfMethod.htm

 1
Author: Diganta Kumar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-02 12:59:52

Desde ES2016 también puedes usar un método ligeramente mejor / más fácil / más elegante:

if (referrer.includes("Ral")) { ... }

O

if (referrer.toLowerCase().includes(someString.toLowerCase())) { ... }

Aquí hay una comparación de .indexOf() y .includes(): https://dev.to/adroitcoder/includes-vs-indexof-in-javascript

 1
Author: Łukasz Matuszewski,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-22 00:51:33

Es 2016, y no hay una manera clara de cómo hacer esto? Esperaba un poco de copypasta. Voy a intentarlo.

Notas de diseño: Quería minimizar el uso de memoria y, por lo tanto, mejorar la velocidad, por lo que no hay copia/mutación de cadenas. Supongo que V8 (y otros motores) pueden optimizar esta función.

//TODO: Performance testing
String.prototype.naturalIndexOf = function(needle) {
    //TODO: guard conditions here

    var haystack = this; //You can replace `haystack` for `this` below but I wan't to make the algorithm more readable for the answer
    var needleIndex = 0;
    var foundAt = 0;
    for (var haystackIndex = 0; haystackIndex < haystack.length; haystackIndex++) {
        var needleCode = needle.charCodeAt(needleIndex);
        if (needleCode >= 65 && needleCode <= 90) needleCode += 32; //ToLower. I could have made this a function, but hopefully inline is faster and terser
        var haystackCode = haystack.charCodeAt(haystackIndex);
        if (haystackCode >= 65 && haystackCode <= 90) haystackCode += 32; //ToLower. I could have made this a function, but hopefully inline is faster and terser

        //TODO: code to detect unicode characters and fallback to toLowerCase - when > 128?
        //if (needleCode > 128 || haystackCode > 128) return haystack.toLocaleLowerCase().indexOf(needle.toLocaleLowerCase();
        if (haystackCode !== needleCode)
        {
            foundAt = haystackIndex;
            needleIndex = 0; //Start again
        }
        else
            needleIndex++;

        if (needleIndex == needle.length)
            return foundAt;
    }

    return -1;
}

Mi razón para el nombre:

  • Debe tener indexOf en el nombre
  • No agregue un sufijo-Of se refiere al siguiente parámetro
  • No use "caseInsensitive" eso es taaaaa largo
  • "natural" es un buen candidato, porque las comparaciones entre mayúsculas y minúsculas predeterminadas no son naturales para los humanos en primer lugar.

Por qué no...:

  • toLowerCase() - posibles llamadas repetidas a minúsculas en la misma cadena.
  • RegExp - difícil de buscar con variable. Incluso el objeto RegExp es incómodo tener que escapar caracteres
 0
Author: Todd,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-10 10:52:40

Aquí está mi opinión:

Script:

var originalText = $("#textContainer").html()
$("#search").on('keyup', function () {
  $("#textContainer").html(originalText)
  var text = $("#textContainer").html()
  var val = $("#search").val()
  if(val=="") return;
  var matches = text.split(val)
  for(var i=0;i<matches.length-1;i++) {
    var ind =  matches[i].indexOf(val)
    var len = val.length
      matches[i] = matches[i] + "<span class='selected'>" + val + "</span>"
  }
  $("#textContainer").html(matches.join(""))

HTML:

<input type="text" id="search">
<div id="textContainer">
lorem ipsum is simply dummy text of the printing and typesetting industry. lorem ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of letraset sheets containing lorem ipsum passages, and more recently with desktop publishing software like Aldus pagemaker including versions of lorem ipsum.</div>

Codepen

 0
Author: Michael Seltenreich,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-07 22:26:35