最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to replace the value attribute in an HTML string? - Stack Overflow

programmeradmin0浏览0评论

Given:

let mystr = "<input class=\"text-box single-line\" id=\"item_Name\" name=\"item.Name\" type=\"text\" value=\"Luis Tiant\">";

Given:

let mystr = "<input class=\"text-box single-line\" id=\"item_Name\" name=\"item.Name\" type=\"text\" value=\"Luis Tiant\">";

I'd like to remove the text in the value param "Luis Tiant" using JS.

To be clear: I want to change value="Luis Tiant" to value="" in the string itself. This is a string not yet a DOM element. After I remove the value then I'll add it to the DOM.

Share Improve this question edited Feb 15, 2021 at 14:39 pretzelhammer 15.2k16 gold badges54 silver badges104 bronze badges asked May 22, 2020 at 13:51 Carlos VasquezCarlos Vasquez 211 silver badge5 bronze badges 4
  • document.getElementById("item_Name").value = ""; – PajLe Commented May 22, 2020 at 13:54
  • 1 Does this answer your question? How to remove/change an input value using javascript – Flori Bruci Commented May 22, 2020 at 13:55
  • thank you for the reply. This won't work. I apologized for not be more clear. mystr is a string and I want to change value="Luis Tiant" to value="" in the string – Carlos Vasquez Commented May 22, 2020 at 13:58
  • @CarlosVasquez I've updated my answer below to meet your new requirements. – pretzelhammer Commented May 22, 2020 at 14:12
Add a ment  | 

4 Answers 4

Reset to default 1

Get the input element and set its value to '' (empty string).

Example below clears the input value after 2 seconds, so you can see it in action:

setTimeout(() => {
  document.querySelector('input').value = '';
}, 2000);
<input class="text-box single-line" id="item_Name" name="item.Name" type="text" value="Luis Tiant">

Update

Question above has been clarified. If you'd like to replace the value attribute in the string itself you can acplish that using regex and the replace method like so:

let string = "<input class=\"text-box single-line\" id=\"item_Name\" name=\"item.Name\" type=\"text\" value=\"Luis Tiant\">";

console.log(string);

let newString = string.replace(/value=\".*\"/, "value=\"\"");

console.log(newString);

By initializing the ID you can do this as well.

document.getElementById("item_Name").value = "Your new Value Here";

Instead of setting a variable equal to a string of html, then using string manipulation to change the element attributes, I'd suggest using the Document.createElement() method and related APIs to programmatically create the html element. Then you'll have access to methods like Element.removeAttribute()

let mystr = "<input class="text-box single-line" id="item_Name" name="item.Name" type="text" value="Luis Tiant">"
var res = mystr.match(/value=\".*\"/g);
var str = mystr.replace(res, 'value=""');

发布评论

评论列表(0)

  1. 暂无评论