I'm currently using a function to check if a URL has correctly escaped two different characters: . and /.

To escape a character within a string, it requires 2 preceding \'s in the string (i.e.: \\. or \\/).

Here is the code I'm currently using. As you can see I'm matching the string with some regex, and then for every element returned I check if the first character of the string is \.

I feel this could be simplified, how can I make this better and avoid looping through all elements returned by match?

function isValidEscapedString(value) {
  return (value.match(/.?[./]/g)||[]).every((escape) => escape[0] === '\\');

console.log(isValidEscapedString('')); // true
console.log(isValidEscapedString('https://stackoverflow.com')); // false
console.log(isValidEscapedString('https:\/\/stackoverflow\.com')); // false
console.log(isValidEscapedString('https://stackoverflow\\.com')); // false
console.log(isValidEscapedString('https:\\/\\/stackoverflow\\.com')); //true

The examples in the code are working as intended.

  • \$\begingroup\$ Why are you specifically escaping . and /? For RegExp constructor or something else? \$\endgroup\$
    – adiga
    Aug 13, 2020 at 8:28
  • \$\begingroup\$ @adiga yes that's right. Somewhere in one of our other microservices it's used like that. \$\endgroup\$ Aug 13, 2020 at 8:35
  • \$\begingroup\$ There are other meta characters which can be present in a URL like -?[]()*+. You don't want to check for those? \$\endgroup\$
    – adiga
    Aug 13, 2020 at 8:40
  • \$\begingroup\$ @adiga you're probably right. We're currently porting a legacy RoR project into Typscript and that's how it's been done for years. And would appear those other characters haven't been used yet. lol \$\endgroup\$ Aug 13, 2020 at 8:43
  • 1
    \$\begingroup\$ I have couple more questions. By, "without query params", your url will always be in the form of https://domain-name.com or can it have a path after that: https://domain-name.com/path? Do you get the escaped string as input or do you have access to unescaped string? If you have the unescaped string, there is already a function for escaping all the metacharacters. \$\endgroup\$
    – adiga
    Aug 13, 2020 at 11:22

1 Answer 1


What about, instead of search for every . and / and check the predecessor character, you write a regexp that find a . and / that don't have \\ before?

This way, you can avoid the loop and the short circuit to an array

function isValidEscaped(str) {
  const pattern = /[^\\]{2}[./]/g;
  return str.search(pattern) === -1; 


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.