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

javascript - String replacing in a div - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question edited Sep 17, 2011 at 18:24 pimvdb 155k80 gold badges311 silver badges356 bronze badges asked Sep 17, 2011 at 18:15 X10nDX10nD 22k46 gold badges113 silver badges154 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 14

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)

  1. 暂无评论