Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Calculadora

0

107
Vistas
JS: Can someone explain me this regex and is it possible to write without regex exp?

I do not have experience with regex, I found this in code and I am trying to understand it. This is regexp: (/[a-z\d]+=[a-z\d]+/gi); And context in which is used is next:

const queryString = window.location.search;
let matches = queryString.match(/[a-z\d]+=[a-z\d]+/gi);
let count = matches ? matches.length : 0;

Also, I am interested is this possible to write in a different way, not to use regexp?

7 months ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

It's checking how many query strings are in the url.

/[a-z\d]+=[a-z\d] says any letter or digit between an = and another letter or digit should match.

The gi part means it is global case insensitive.

  • g = global, match all instances of the pattern in a string, not just one
  • i = case-insensitive (so, for example, /a/i will match the string "a" or "A".

const urlQueryString = 'https://test.com/page?name=ferret&color=purple'
let matches = urlQueryString.match(/[a-z\d]+=[a-z\d]+/gi);
let count = matches ? matches.length : 0;

console.log(count) // --> 2 name=ferret color=purple

There is a tool available here allowing you to test the regex.

7 months ago · Juan Pablo Isaza Denunciar

0

This code will count amount of query parameters present in string. However, you can use URLSearchParams class for counting entries in query strings.

// URL: https://example.com/?query1=value&query2=value
const searchParams = new URLSearchParams(window.location.search);

// This row will map iterator into array
// [ ['query1', 'value'], ['query2', 'value'] ]
const entriesArray = [...searchParams.entries()];

// 2
console.log(entriesArray.length);
7 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar empleo Planes Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2023 PeakU Inc. All Rights Reserved.