0

I am trying to copy a specific part of a sentence from a div to another and input it to another area using JavaScript.

<div id="copyfromhere">This is +how+ it works.</div>
<div id="pastehere"></div>

I'd like to copy the part in between the + symbols. The + symbols are included in the original sentence.

komelon12
  • 3
  • 1

2 Answers2

0

you can get the text from div and split it based on '+', which will return the array, then you can access that arrays 2nd value indexed at 1.

var pastehereDiv = document.querySelector("#pastehere");
var copyfromDiv = document.querySelector("#copyfromhere")
pastehereDiv.textContent = copyfromDiv.textContent.split('+')[1];
sanjiv saini
  • 356
  • 1
  • 3
  • 11
0

var copy = function() {
  // grab the origin and destination divs
  var origin = document.getElementById("copyfromhere");
  var destination = document.getElementById("pastehere");
  
  // get the text from the origin, split on "+" and then get the second element in the array
  var text = from.innerText.split("+")[1];
  // apply that text to the destination div
  destination.innerText = text;
}
<div id="copyfromhere">This is +how+ it works.</div>
<div id="pastehere"></div>

<button id="copy" onClick="copy()">Copy</button>

Obviously this will only work if there aren't any other +s in your origin div.

larz
  • 5,724
  • 2
  • 11
  • 20