Regular Expressions. Help

0

I'm just getting into this from regular expressions. And I want to try to do as a word finder, to the most whatsapp style. What do you place to search for a word or letter and it shows you all the coincidences.

The question is as follows.

let regex1 = new RegExp(/l/gi);
let texto = "Cualquier texto";
let array;
while((array = regex1.exec(str1)) !== null){
let index = regex1.lastIndex;
let oracion = str1.split(' ');

console.log('Encontramos una coincidencia en ${array[0]}. 
Esta en  ${index} '${oracion[regex1]}'');

There the exec finds me the letter l in the sentence and returns to me the index of where that letter is. But I want you to also return the entire word to me.

That code will take you out of the DevMoz examples page. I am also trying to split and configuring the regular expression well with all the necessary symbols but I still do not hit the spot.

I hope you understand me and can help me.

    
asked by Francisco Gomez 27.11.2018 в 00:11
source

1 answer

0

You could try the following using /\w*l\w*/gi in the following way:

regex = new RegExp(/\w*l\w*/gi);
texto = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent iaculis elit mi."

Which would result in the following:

regex.exec(texto)
["Lorem", index: 0, input: "Lorem ipsum dolor sit amet, consectetur adipiscing… elit mi. Morbi ut leo maximus, lobortis elit vel", groups: undefined]
regex.exec(texto)
["dolor", index: 12, input: "Lorem ipsum dolor sit amet, consectetur adipiscing… elit mi. Morbi ut leo maximus, lobortis elit vel", groups: undefined]
regex.exec(texto)
["elit", index: 51, input: "Lorem ipsum dolor sit amet, consectetur adipiscing… elit mi. Morbi ut leo maximus, lobortis elit vel", groups: undefined]

And to retrieve the word and index you only have to do the following:

palabra = regex.exec(texto)
palabra[0]
// "Lorem"
palabra['index']
// 0

\w Matches any letter, digit, or underscore. Equivalent to using [a-zA-Z0-9_] .

    
answered by 27.11.2018 / 00:36
source