-2

I have a variable called location that users put a URL in. I was able to take that URL and convert it to an HTML link. I found out though if the user puts a link in with a space, where there should be a %20, the HTML link breaks. Here is my code to try and fix any blank spaces but it doesn't seem to be working.

var medias = []
var type = FilePlanForm.Items[i].Fields["Media Location"].Value;
var location = FilePlanForm.Items[i]["Media Location"].Value;
if ((location != null) && (location.indexOf(/\s/g) > -1)) {
  location.replace(/\s/g, "%20");
}

if ((type == null) && (location != null) && (location.length >0)) { medias.push("Medias Type not selected" + " - " + location); }
else if((location != null) && (location.length > 0)) {medias.push(type + " - " + location); }

var type = FilePlanForm.Items[i].Fields["Media Location 2"].Value;
var location = FilePlanForm.Items[i]["Media Location 2"].Value;
if ((location != null) && (location.indexOf(/\s/g) > -1)) {
  location.replace(/\s/g, "%20");
}

if ((type == null) && (location != null) && (location.length >0)) { medias.push("Medias Type not selected" + " - " + location); }
else if((location != null) && (location.length > 0)) {medias.push(type + " - " + location); }

I have also tried using the encodeURI function, but if the user enters the URL correctly and without any spaces, it breaks the URL.

Thanks

Schmit
  • 41
  • 5
  • 12
  • the above duplicate also covers the [URL interface](https://developer.mozilla.org/en-US/docs/Web/API/URL) in this anser: https://stackoverflow.com/a/68210862/13762301 – pilchard Apr 13 '22 at 12:26

1 Answers1

1

This is a good use-case for window.URL.

Do:

const url = new URL('https://example.com/correct%20part/incorrect part');
console.log(url.href);
Lux
  • 17,835
  • 5
  • 43
  • 73
  • Hey, thank you! This seems like it will work. It appears to fail though if one of the values is left blank. Might need to add some kind of if statement in there – Schmit Apr 13 '22 at 12:35
  • @Schmit when what is blank? in my example you explicitly can see that it *does* handle blank parts correctly. – Lux Apr 13 '22 at 22:44