[英]How do I replace the html objects with it's text content?
I'm trying to replace link parameters with the query strings and I'm a noob when it comes to web dev 我正在尝试用查询字符串替换链接参数,但对于Web开发人员来说,我是一个菜鸟
I've tried String(), object.textContent() and some more things but can't seem to get what I want 我已经尝试过String(),object.textContent()和其他一些东西,但似乎无法获得我想要的东西
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]
To get the value of an input
, you use its value
. 要获取input
的值 ,请使用其value
。 Also, in query strings, you must encode query parameters with encodeURIComponent
¹. 另外,在查询字符串中,必须使用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. 如果您需要替换其中的每一个( replace1
, replace2
),而不仅仅是在显示的第一个位置,请参阅此问题的答案 。
Of course, with the code you've shown, it would make more sense not to use replace
at all: 当然,通过显示的代码,完全不使用replace
会更有意义:
link = "https://someWebsite?phone=" + encodeURIComponent(phone.value) +
"&message=" + encodeURIComponent(message.value);
Or with ES2015+: 或搭配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. ¹您也必须对名称进行编码,但是encodeURIComponent("phone")
是"phone"
, encodeURIComponent("message")
是"message"
,所以...但是,如果其中还有其他字符,例如[]
,则需要对其进行编码。
In jQuery we use backticks and ${} for string interpolation: 在jQuery中,我们使用反引号和$ {}进行字符串插值:
`some text ${replacedtext} some other text`
If you're using vanilla javascript use + signs for string interpolation: 如果您使用香草javascript,请使用+符号进行字符串插值:
"some text" + replacedtext + "some other text"
Hope this helps 希望这可以帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.