Skip to content
Advertisement

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)           

Advertisement

Answer

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.

Advertisement