Matthew Macarty
Matthew Macarty

Reputation: 3

regex and converting strings to array and back and forth Javascript

I am reading data from a text file and I am interested in a specific pattern that I have isolated with the following:

 cleanString = queryString.match(/^NL.*/gm);

This results in the array:

["NL:What are the capitals of the states that border the most populated states?",
"NL:What are the capitals of states bordering New York?",
"NL:Show the state capitals and populations.", 
"NL:Show the average of state populations.", 
"NL:Show all platforms of Salute generated from NAIs with no go mobility."]

I then want to get rid of all patterns matching NL: so I am left with just a natural language question or statement. To accomplish this, I convert the array to a string , and then use .split() to create the desired array like so:

var nlString = cleanString.toString();
var finalArray = nlString.split(/NL:/gm);

There are two problems I am having. 1. I end up with an extra value of an empty string at index [0] in the resulting array, and 2. I now have a comma literal appended to the strings in the array:

["", "What are the capitals of the states that border the most populated states?,",
"What are the capitals of states bordering New York?,",
"Show the state capitals and populations.,", 
"Show the average of state populations.,", 
"Show all platforms of Salute generated from NAIs with no go mobility."]

How can I eliminate these problems? Also If someone has a more elegant approach to reading a big ugly text file delimited by line breaks and isolating strings of interest I am all eyes.

Thanks in advance for any suggestions.

Upvotes: 0

Views: 432

Answers (3)

user1636522
user1636522

Reputation:

Warning : map is not supported by IE8 and below. Here is an alternative :

var array = string.split(/\n*NL:/);
array.shift(); // that's it

Demo here : http://jsfiddle.net/wared/BYgLd/.

Upvotes: 0

10 cls
10 cls

Reputation: 1425

var finalString = nlString.replace(/NL:/gm, '');

Upvotes: 0

adeneo
adeneo

Reputation: 318182

You don't have to convert the array to a string, then remove the NL: strings and convert back to an array, just iterate over the array and remove that string in each index

var arr = arr.map(function(el) {return el.replace('NL:','');});

FIDDLE

a regular for loop would also work if older browsers is an issue

Upvotes: 2

Related Questions