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.
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;
}
.
and/
? ForRegExp
constructor or something else? \$\endgroup\$-?[]()*+
. You don't want to check for those? \$\endgroup\$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\$