Skip to content

Posts tagged javascript

Posts under this tag. Back to all posts when you want the full stream.

Posts

4 posts under this tag.

@latest_post

TIL: Escape a string for a JavaScript regular expression

Text supplied at runtime can contain characters with special meaning in a regular expression. For example:

JavaScript
const input = "[Hello?](World)!!!"

Modern JavaScript provides RegExp.escape() for turning that text into a literal pattern:

JavaScript
const escaped = RegExp.escape(input)
// "\\[Hello\\?\\]\\(World\\)\\x21\\x21\\x21"
const pattern = new RegExp(escaped)
pattern.test(input)
// true

RegExp.escape() also handles edge cases that are easy to miss in a hand-written replacement. Check your runtime compatibility before using it.

Updated 1 min read
Start reading Read more