# Check whether '.' and '/' are escaped properly

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.

• Why are you specifically escaping . and /? For RegExp constructor or something else? – adiga Aug 13 at 8:28
• @adiga yes that's right. Somewhere in one of our other microservices it's used like that. – kemicofa ghost Aug 13 at 8:35
• There are other meta characters which can be present in a URL like -?[]()*+. You don't want to check for those? – adiga Aug 13 at 8:40
• @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 – kemicofa ghost Aug 13 at 8:43
• 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. – adiga Aug 13 at 11:22

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?
function isValidEscaped(str) {
}