开发者

String replacing in a div

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

Wha开发者_Go百科t is the correct syntax to replace a word in a div?


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 iteration
  • txt is the current text content of the current element

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜