Carlos Vasquez
Carlos Vasquez

Reputation: 21

How to replace the value attribute in an HTML string?

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.

Upvotes: 0

Views: 6246

Answers (4)

Razvan
Razvan

Reputation: 319

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=""');

Upvotes: 1

pretzelhammer
pretzelhammer

Reputation: 15105

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 accomplish 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);

Upvotes: 1

Dylan Landry
Dylan Landry

Reputation: 1290

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()

Upvotes: 1

Jesper Martinez
Jesper Martinez

Reputation: 631

By initializing the ID you can do this as well.

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

Upvotes: 1

Related Questions