I want to replace a particular string in #TextArea1
. This happens when a button is clicked.
Trying it out with the below code, but unable to get it work:
$('#TextArea1').text().replace("wef","--");
What is the correct syntax to replace a word in a div
?
Set the innerHTML Property of an Element querySelector('div') div. innerHTML = "My new text!"; to select the div with querySelector . And then we can set the innerHTML to a new string.
Use the textContent property to change the text of a div element, e.g. div. textContent = 'Replacement text' . The textContent property will set the text of the div to the provided string, replacing any of the existing content. Here is the HTML for the examples in this article.
The Element property innerHTML gets or sets the HTML or XML markup contained within the element. To insert the HTML into the document rather than replace the contents of an element, use the method insertAdjacentHTML() .
The replace() method searches a string for a value or a regular expression. The replace() method returns a new string with the value(s) replaced.
Pass a function to the text()
[docs] method that returns the value you want set:
$('#TextArea1').text(function( i, txt ) {
return txt.replace("wef","--");
});
The function parameters are as follows:
i
is the index of the current element in the iterationtxt
is the current text content of the current elementThe value returned from the function will be set as the new value for the current element.
You are close, try this:
$('#TextArea1').text($('#TextArea1').text().replace(/wef/g,"--"));
Or an optimized one
var $textarea = $('#TextArea1');
$textarea.text($textarea.text().replace(/wef/g,"--"));
If it's a textarea
element, you would do:
var $textarea = $('#TextArea1');
$textarea.val($textarea.val().replace(/wef/g,"--"));
You have set the text also:
var text = $('#TextArea1').text().replace("wef","--");
$('#TextArea1').text(text);
or, using a function:
$('#TextArea1').text(function(index, text) {
return text.replace("wef","--");
});
Note: if this is a <textarea>
, use val()
instead of text()
.
var text = $('#TextArea1').val().replace("wef","--");
$('#TextArea1').val(text);
replace()
creates a new string and returns it, so it's getting returned into thin air. You need to grab the new string and send it back into the textbox. This jsfiddle shows how.
<textarea id="t">
hello
</textarea>
var text = $('#t').text();
text = text.replace('h', 'b');
$('#t').text(text);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With