skip to Main Content

How to get specific word from string array ?

let array= [
  'age 19 - Donna',
  'age 20 - James'
];
let getNumber = [] //19 and 20
let getName= [] // Donna and James
for(let i = 0; i < array.length; i++){
 getNumber[i] = text[i].split(" ", 2)[1];
  getName[i] = text[i].split(",", 5);
}
document.getElementById("demo").innerHTML = getNumber;
document.getElementById("demo2").innerHTML = getName;

current result:

19,20

age 19 – Donna,age 20 – James

desired result:

19,20

Donna,James

2

Answers


  1. split return array, so catch your desire result based on index of that array.

    Example:

    let array = [
      'age 19 - Donna',
      'age 20 - James'
    ];
    
    let getNumber = [] //19 and 20
    let getName = [] // Donna and James
    
    for (let i = 0; i < array.length; i++) {
      let val = array[i];
      getNumber[i] = val.split(" ")[1];
      getName[i] = val.split(" ")[3];
    }
    
    document.getElementById("demo").innerHTML = getNumber;
    document.getElementById("demo2").innerHTML = getName;
    <div id="demo"></div>
    <div id="demo2"></div>
    Login or Signup to reply.
  2. Using match with a a regular expression might be a little simpler.

    const demo = document.getElementById('demo');
    const demo2 = document.getElementById('demo2');
    
    const array = [
      'age 19 - Donna',
      'age 20 - James'
    ];
    
    const getNumber = [];
    const getName= [];
    
    // Create a regex that picks up a group of numbers
    // and a group of letters
    const re = /(d+) - ([a-zA-Z]+)/;
    
    for (let str of array) {
    
      // `match` on the string with the regex,
      // destructuring the number from the first group
      // and the name from the second group
      const [ , number, name ] = str.match(re);
    
      // Push the values into the arrays
      getNumber.push(number);
      getName.push(name);
    }
    
    demo.textContent = getNumber;
    demo2.textContent = getName;
    <div id="demo"></div>
    <div id="demo2"></div>

    Additional documentation

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search