Take the 2 position of a string in an array

Asked

Viewed 460 times

0

I’m having a hard time picking up only the "second position" of each string in an array set.

Example: when playing the urls below:

https://www.devs.com/produto/chave1, https://www.devs.com/produto/chave2

I want to retrieve only the suffix of each array that in this case would be, "Chave1", "Chave2" and so on regardless of the amount of links I place.

I tried to do here, but when running the code below, it searches for the 2 items:

[ " https://www.devs.com", "Chave1" ],

function myFunction() {
  
  
  var exibir = document.getElementById("myTextarea").value;

  result = exibir.split(',').map(s => s.split('/produto/'))
  
  console.log(result)

  let display = result

  document.getElementById("demo").innerHTML = result;
  
}
<!DOCTYPE html>
<html>
<body>

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

Address:<br>
<textarea id="myTextarea">
 https://www.devs.com/produto/chave1,
https://www.devs.com/produto/chave2
</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>

Does anyone know how I do to capture only what comes after /product/ which in case would be "Chave1", Chave2", and so on?

2 answers

0

The split splits your string into two parts, as you only need the second part it is better to apply a substring that way:

var link = 'https://www.devs.com/produto/chave1'
var pagina = '/produto/'

var chave = link.substring(link.search(pagina) + pagina.length, link.length)
console.log(chave)

0


Just use a map to scroll through item by item from array and then, in each item, use the function split to catch the last group separated by /:

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

String.prototype.split()

The method split() divides an object String in a array of strings by separating the string in substrings.


Array.prototype.map()

The map() method invokes the callback function passed by argument to each Array element and returns a new Array as a result.

var numbers = [1, 4, 9];
var roots = numbers.map(Math.sqrt);
// roots é [1, 2, 3], numbers ainda é [1, 4, 9]
  • Thanks man, thank you so much for the explanation!

  • @Thiago if the answer helped you, do not forget to accept it as correct for your questioning, thus helping people with similar doubts to find it.

  • Sure, thanks a bro!

  • doubt here, I’m cracking my head to put the input of textarea in the const links, type I want the user to put all the links in the text box and appear in the browser, as I do this?

Browser other questions tagged

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