const isUrl = string => {
const matchPattern = /^https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$/gm
return matchPattern.test(string)
}
let myUrl = new URL('https://google.com')
// evil
const evilpathname = 'https://not-google.com'
if (evilpathname) myUrl.pathname = evilpathname
console.log('Not validated URL', myUrl.toString())
// good
myUrl = new URL('https://google.com')
if (evilpathname && !isUrl(evilpathname)) myUrl.pathname = goodpathname
console.log('Validated URL', myUrl.toString())