Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

126
Visualizações
How to retrieve a random value from an array that has values separate by a new line

I am a complete newbie at JS and currently using it in a testing capacity along with the Karate framework to perform some UI testing. I am having the following problem:

There is a dropdown that has the following HTML:

<select class=id="CarId" name="CarId" aria-describedby="CarId-error" aria-invalid="false" xpath="1">
<option value="1">Mercedes</option>
<option value="2">BMW</option>
<option value="3">Lexus</option>
<option value="4">Honda</option>
<option value="5">Toyota</option>
<option value="6">VW</option>
</select>

I used the following Karate method to get all text values under the dropdown:

def grabValues = scriptAll('#CarId', '_.textContent')

Once printed, the array look like this:

[
  "Mercedes\nBMW\nLexus\nHonda\nToyota\nVW\n"
]

console.log(Math.floor(Math.random() * (grabValues.length-1)))

When printed, it keeps giving me 0.0. I am assuming this is because the array contains new lines vs comma delimitated? If so, how can I get rid of the new lines and replace with commas?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

What you want is to get the text from each <option>

def grabValues = scriptAll('#CarId option', '_.textContent')

This will give you an array of text values like

["Mercedes","BMW","Lexus","Honda","Toyota","VW"]

To get a random index you would use

Math.floor(Math.random() * grabValues.length)
about 4 years ago · Juan Pablo Isaza Relatório

0

One line code is console.log(myArr[0].split('\n'))

OR

Let's assume : The array of String is stored in myArr

let myArr = ["ABC\nDEF\nGHI\nJKL\nMNO\nPQR\nSTU\nVWX\nYZA\n"]

To get the string from the array

let stringOfArr = myArr[0]

Storing the new array from the stringOfArr deleminated by '\n' in newArray

let newArray = stringOfArr.split('\n')

console.log(newArray)
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda