skip to Main Content

I have a form with input fields like this:

lines[1][config][options][346]

I can get the last part with this:

var name = 'lines[0][config][options][343]';
let ido = name.lastIndexOf("["),
  idc = name.lastIndexOf("]"),
  index = name.substring(ido + 1, idc);
console.log(index);

But what if i am interested in first, second, third etc. name?

3

Answers


  1. js regular expression solution

    const str = 'lines[0][config][options][343]';
    const reg = /[([0-9]+|[a-z]+|[A-Z]+)]/g;
    const groups = [];
    
    str.replaceAll(reg, group => {
      let value = group.replace(`[`, ``).replace(`]`, ``)
      groups.push(value)
      return ''
    });
    
    console.log(`groups =`, groups);
    // ['0', 'config', 'options', '343']
    
    // one more thing ✅
    const arr = groups.map(item => isNaN(item) ? item : parseInt(item))
    console.log(`arr =`, arr);
    // [0, 'config', 'options', 343]
    Login or Signup to reply.
  2. Use a simple regular expression:

    const input = `lines[1][config][options][346]`;
    const values = input.match(/(?<=[)[^]]+(?=])/g);
    
    console.log(values);    // ["1", "config", "options", "346"]
    console.log(values[1]); // "config"

    here’s explained on Regex101.com, basically:

    expression description
    (?<=[) (positive lookbehind) Preceded by [
    [^]]+ not ] one or more times
    (?=]) (positive lookahead) followed by ]
    g (Global match flag)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search