Reputation: 13
I'm trying to replace link parameters with the query strings and I'm a noob when it comes to web dev
I've tried String(), object.textContent() and some more things but can't seem to get what I want
here's my code:
link="https://someWebsite?phone=replace1&message=replace2"
link = link.replace("replace1",phone); //phone is an input box returned by document.getElementByID() method
link = link.replace("replace2",message); //message is a text area returned by document.getElementByID() method
expected link: https://someWebsite?phone=123456&mesaage=somemessage
actual link: https://someWebsite?phone= [object HTMLInputElement]&message=[object HTMLTextAreaElement]
Upvotes: 0
Views: 60
Reputation: 61
In jQuery we use backticks and ${} for string interpolation:
`some text ${replacedtext} some other text`
If you're using vanilla javascript use + signs for string interpolation:
"some text" + replacedtext + "some other text"
Hope this helps
Upvotes: 0
Reputation: 1074248
To get the value of an input
, you use its value
. Also, in query strings, you must encode query parameters with encodeURIComponent
¹. So:
link="https://someWebsite?phone=replace1&message=replace2"
link = link.replace("replace1",encodeURIComponent(phone.value));
link = link.replace("replace2",encodeURIComponent(message.value));
Also note that each of those will replace the first occurrence, not all occurrences. See this question's answers if you need to replace each of those (replace1
, replace2
) in more than just the first place it appears.
Of course, with the code you've shown, it would make more sense not to use replace
at all:
link = "https://someWebsite?phone=" + encodeURIComponent(phone.value) +
"&message=" + encodeURIComponent(message.value);
Or with ES2015+:
link = `https://someWebsite?phone=${encodeURIComponent(phone.value)}&message=${encodeURIComponent(message.value)}`;
¹ You have to encode the names, too, but encodeURIComponent("phone")
is "phone"
and encodeURIComponent("message")
is "message"
, so... But if you had other characters in there, such as []
, you'd need to encode them.
Upvotes: 2