Philipgth
Philipgth

Reputation: 3

How to replace value of textarea with innerHTML of 2 different ID

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

How do I replace the textarea value with innerHTML of #re with #wi. where result will be

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

Note that the innerHTML will change and I cannot use normal string replace

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

Upvotes: 0

Views: 396

Answers (2)

CumminUp07
CumminUp07

Reputation: 1978

Seeing as how you tagged jquery, you can use this

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>

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337627

To achieve this you need to first retrieve the text of the relevant div elements. Then you can build a RegExp object before doing the actual replacement. Try this:

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

Upvotes: 2

Related Questions