0

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.

4
  • document.getElementById("item_Name").value = ""; Commented May 22, 2020 at 13:54
  • 1
    Does this answer your question? How to remove/change an input value using javascript 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 Commented May 22, 2020 at 13:58
  • @CarlosVasquez I've updated my answer below to meet your new requirements. Commented May 22, 2020 at 14:12

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

1 Comment

@CarlosVasquez if this answers your question please accept the answer by clicking on the gray checkmark under the answer's score, thanks!
1

By initializing the ID you can do this as well.

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

Comments

1

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.