0

I am using the following regex to seach a sentence and want to match only values that are followed by a period. I am confused to why the following regex is true since the ta isnt followed by a period. How would I change it so doesnt match?


let text = 'Paracetamol takes up to an hour to work. to '

let regex = new RegExp("ta" + ".", "i")
console.log(regex.test(text))

crmarc
  • 13
  • 4
  • 3
    In a regex some characters have special meanings. The period is one of them; it means match any character. Try escaping it with a backslash: \. – Charles Savoie Jun 18 '23 at 17:48
  • Does this answer your question? [Regex to match a period](https://stackoverflow.com/questions/22951369/regex-to-match-a-period) – Seblor Jun 18 '23 at 17:51
  • I changed it to this and it still isnt working,. ```let text = 'Paracetamol takes up to an hour to work. to ' let regex = new RegExp("ta" + "\.", "i") console.log(regex.test(text))``` – crmarc Jun 18 '23 at 19:03
  • 1
    You escaped the period for the string, but not the regex, you'll have to write your regex with a literal, or escape the backslash with another backslash – Seblor Jun 18 '23 at 19:10
  • 1
    As Seblor said, this should do the thing: `let regex = new RegExp("ta"+"\\.", "i");` – tsgrgo Jun 18 '23 at 19:23
  • Ok thanks I forgot I needed two backslashs when using the regex constructor – crmarc Jun 18 '23 at 20:14

0 Answers0