How to associate an Array in a textarea?

Asked

Viewed 116 times

0

As I put the value of const links to pull from my "textarea" tag, the code works as expected, runs on the right console, but I want that instead of putting the information in the const links, the user can put in the "textarea" inpu field and appear on the screen. Someone knows how to do it?

function myFunction() {

var elemento = document.getElementById("myTextarea").value;
const links = ['https://www.devs.com/produto/chave1', 'https://www.devs.com/produto/chave2'];

const chaves = links.map((link) => link.split('/')[link.split('/').length - 1]);
console.log(chaves);

}
<!DOCTYPE html>
<html>
<body>

<h3>A demonstration of how to access a TEXTAREA element</h3>

Address:<br>
<textarea id="myTextarea">
</textarea>

<p>Click the button to get the content of the text area.</p>

<button type="button" onclick="myFunction()" >Try it</button>

<p id="demo"></p>


</body>
</html>

  • Would the array be typed in the same format as a javascript expression? If so, you can convert it to json. Eval would also be an option if this does not pose a security threat.

1 answer

1


I took the liberty of changing your function a little, but I believe it will solve your problem. In this case the data is removed from the URL via regex and kept only the key.

The replace(/\n/g, '') is only to remove line breaks in case the user writes an item on each line, but the code should work both ways.

function myFunction() {
  let exibir = document.getElementById("myTextarea").value;
  let urls = exibir.split(',');
  let chaves = [];
  urls.map(url => chaves.push(url.replace(/(.*?)produto\//g, '').replace(/\n/g, '')));
  console.log(chaves);
  document.getElementById("demo").innerHTML = chaves[1];
}
  • Man, I can understand here, thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.