Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

264
Vistas
Regex to match string in a sentence

I am trying to find a strictly declared string in a sentence, the thread says:

Find the position of the string "ten" within a sentence, without using the exact string directly (this can be avoided in many ways using just a bit of RegEx). Print as many spaces as there were characters in the original sentence before the aforementioned string appeared, and then the string itself in lowercase.

I've gotten this far:

let words = 'A ton of tunas weighs more than ten kilograms.'

function findTheNumber(){

         let regex=/t[a-z]*en/gi;
         let output = words.match(regex)
         console.log(words)
         console.log(output) 
}

console.log(findTheNumber())

The result should be:

input  = A ton of tunas weighs more than ten kilograms.
output =                                 ten(ENTER)           
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You could try a regex replacement approach, with the help of a callback function:

var input = "A ton of tunas weighs more than ten kilograms.";
var output = input.replace(/\w+/g, function(match, contents, offset, input_string)
{
    if (!match.match(/^[t][e][n]$/)) {
        return match.replace(/\w/g, " ");
    }
    else {
        return match;
    }
});
console.log(input);
console.log(output);

The above logic matches every word in the input sentence, and then selectively replaces every word which is not ten with an equal number of spaces.

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can use

let text = 'A ton of tunas weighs more than ten kilograms.'

function findTheNumber(words){
    console.log( words.replace(/\b(t[e]n)\b|[^.]/g, (x,y) => y ?? " ") )
}
findTheNumber(text)

The \b(t[e]n)\b is basically ten whole word searching pattern.

The \b(t[e]n)\b|[^.] regex will match and capture ten into Group 1 and will match any char but . (as you need to keep it at the end). If Group 1 matches, it is kept (ten remains in the output), else the char matched is replaced with a space.

Depending on what chars you want to keep, you may adjust the [^.] pattern. For example, if you want to keep all non-word chars, you may use \w.

about 4 years 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 vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda