0

Using nodejs, I need to extract ALL strings between two characters that are DIFFERENT, and store them in an array for future use. For instance, consider a file, containing a file with the following content.

"type":"multi",
"folders": [
    "cities/",
    "users/"
]

I need to extract the words: cities and users, and place them in an array. In general, I want the words between " and /"

Nicolas El Khoury
  • 5,867
  • 4
  • 18
  • 28
  • I am extremely new to nodejs and javascript. I am using this as an exercise. I found that the way to do it is using the match method. But I am failing at placing the right delimiters – Nicolas El Khoury Sep 06 '16 at 11:58
  • could you add your failing attempt to the question, so we have a common ground to talk – Thomas Sep 06 '16 at 12:06
  • 1
    Does your file actually contain JSON? Or is that YAML? Parse it. – Bergi Sep 06 '16 at 12:09

2 Answers2

2

As Bergi mentions in a comment, this looks suspiciously similar to JSON (javascript object notation.) So I'll write my answer assuming that it is. For your current example to be valid JSON, it needs to be inside object-brackets like this:

{
    "type": "multi",
    "folders": [
        "cities/",
        "users/"
    ]
}

If you parse this:

var parsed_json = JSON.parse( json_string );

// You could add the brackets yourself if they are missing:
var parsed_json = JSON.parse('{' + json_string + '}');

Then all you have to do to get to the array:

var arr = parsed_json.folders;
console.log(arr);

And to fix the annoying trailing slashes we remap the array:

// .map calls a function for every item in an array
// And whatever you choose to return becomes the new array
arr = arr.map(function(item){ 
  // substr returns a part of a string. Here from start (0) to end minus one (the slash).
  return item.substr( 0, item.length - 1 );

  // Another option could be to instead just replace all the slashes:
  return item.replace( '/' , '' );
}

Now the trailing slashes are gone:

console.log( arr );
Community
  • 1
  • 1
ippi
  • 9,857
  • 2
  • 39
  • 50
0

This should work.

"(.+?)\/"
  1. " preceding
  2. 1 or more character (non-greedy)
  3. followed by /"

REGEX101

tk78
  • 937
  • 7
  • 14