I'm using dynamic text based on a URL parameter. Basically, the goal is to select the first word in the URL parameter and insert it into a paragraph. However, in my current code, it selects the first word in the URL parameter and everything else that comes after it.
Destination URL is like this:
https://example.com/?ref=firstWord/blah/blah/blah
I want to select just the firstWord
(excluding /blah/blah/blah
) and insert it into a paragraph. I should mention that firstWord
is a variable wildcard-type of word.
Here's the code that selects the firstWord
and everything else after it:
var url = new URL(window.location.href);
var firstWord = url.searchParams.get("ref");
document.getElementById("firstWord").innerHTML = firstWord;
Welcome to <p id='firstWord'></p>
Here's my attempt to select just firstWord
and discard /blah/blah/blah
:
var url = new URL(window.location.href);
var firstWord = url.searchParams.get("ref").split('/');
document.getElementById("firstWord").innerHTML = firstWord;
Welcome to <p id='firstWord'></p>
However, this does not exclude /blah/blah/blah
. Instead it inserts it into the paragraph like so:
Welcome to firstWord,blah,blah,blah
. I don't understand where the commas came from.
const ref = url.searchParams.get("ref");
const [justTheFirstPart] = ref.split('/');
or:
const justTheFirstPart = ref.split('/')[0];
Will fail if mainParam
is undefined.