如何用2个不同ID的innerHTML替换textarea的值

时间:2017-08-08 15:37:52

标签: javascript jquery

<p id="re">com</p>
<p id="wi">net</p>

<textarea name="sta">
www.example.com
www.test.cOm
www.mess.COM
www.example.com
www.xxxxx.org
www.xxxxxx.org
www.xxxxxx.com
</textarea>

如何使用#wi替换#re的innerHTML的textarea值。 结果将是

www.example.net
www.test.net
www.mess.net
www.example.net
www.xxxxx.org
www.xxxxxx.org
www.xxxxxx.net

请注意,innerHTML会改变,我不能使用普通的字符串替换

textarea.replace(/com/gi, "net");

2 个答案:

答案 0 :(得分:2)

要实现此目的,您需要先检索相关div元素的文本。然后,您可以在进行实际替换之前构建RegExp对象。试试这个:

&#13;
&#13;
var textarea = document.querySelector('textarea');
var match = document.getElementById('re').textContent.trim();
var replacement = document.getElementById('wi').textContent.trim();

textarea.value = textarea.value.replace(new RegExp(match, 'gi'), replacement);
&#13;
<p id="re">com</p>
<p id="wi">net</p>

<textarea name="sta" rows="10">
www.example.com
www.test.cOm
www.mess.COM
www.example.com
www.xxxxx.org
www.xxxxxx.org
www.xxxxxx.com
</textarea>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

看看你如何标记jquery,你可以使用这个

var match = $('#re').text();
var re = new RegExp(match, 'gi');
$('[name="sta"]').val(

    $('[name="sta"]').val().replace(re,$('#wi').text())
);

var match = $('#re').text();
var re = new RegExp(match, 'gi');
$('[name="sta"]').val(
	
	$('[name="sta"]').val().replace(re,$('#wi').text())
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="re">com</p>
<p id="wi">net</p>

<textarea name="sta">
www.example.com
www.test.cOm
www.mess.COM
www.example.com
www.xxxxx.org
www.xxxxxx.org
www.xxxxxx.com
</textarea>