Can you describe what this JavaScript `parseField` function does?

function parseField(field) {
  return field
    .split(/\[|\]/)
    .filter(function(s){ return s });
}

I use this to analyze the form field. And then use it like this:

var required = function(field){
  field = parseField(field);
  // do something
};

What does he do and how does it work?

+4
source share
2 answers

parseFieldaccepts a string, splits it into a list of all substrings between left or right square brackets ( [or ]), and then returns all elements from this list that have at least one character (basically excluding an empty string, "").

  • Regexp is /\[|\]/similar to saying "division by [and ]"
  • array.filter(s => s) - , false. , JavaScript, , , ("").

:

function parseField (field) { // accept a string `field`
  return field
    .split(/\[|\]/) // splits `field` into an array of strings between each `[` or `]`
    .filter(function(s){ return s }) // keep each string only if it is truthy (not empty)
}

console.log(parseField('[stuff][thing]')) //=> ['stuff', 'thing']
console.log(parseField('[]')) //=> []
+2

, , , /\[|\]/, .

x[y/lol - xylol.

+1

Source: https://habr.com/ru/post/1671848/


All Articles