Kaushik
Kaushik

Reputation: 1349

Pick elements from a string and push in array

I have a requirement like this.

Input string Please choose one \n 1. optionA \n 2. optionB \n 3. optionC

Please choose one can be any text can have any text in its place. From this \n till the end of line will have the exact same format including the spacing. The optionA, optionB and optionC are dynamic.

I want to push the optionA, optionB and optionC into an array. I have been trying it out with Regex and Javascript but wasn't successful. How do I do it?

I used _.words from lodash and regex /\.(.*)\\/ . First of all the regex is not returning the word

Help me out

Upvotes: 0

Views: 91

Answers (4)

trincot
trincot

Reputation: 350725

I would suggest using split:

var input = 'Please choose one \n 1. optionA \n 2. optionB \n 3. optionC';
var options = input.split(/\s*?\n\s*\d+\.\s*/).slice(1);
console.log(options);

Upvotes: 1

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

The solution using Array.prototype.match() and Array.prototype.map() functions:

var s = 'Please choose one \n 1. optionA \n 2. optionB \n 3. optionC',
    options = s.match(/\n \d+\. (\w+)/g).map(function(v){
        return v.trim().split(' ')[1];
    });

console.log(options);

Upvotes: 1

Uditha Kasun
Uditha Kasun

Reputation: 11

Try this one ...

var inputString = 'Please choose one\n 1. option_1 \n 2. option_2 \n 3. option_2';
var matchedList = inputString.match(/\b\w*[_]\w*\b/g);
console.log(matchedList);

Output matchedList array

["option_1", "option_2", "option_2"]

Upvotes: 0

Sagar V
Sagar V

Reputation: 12478

Check this. It will work only for text in the formatted you mentioned in your questions.
Since it is not fully clear whether you are using different strings or not, I give you this solution.
If you do so, leave a comment

var str="This can be any string ending with\n 1. any_option \n 2. can_be_placed \n 3. without_space";
var opt=str.replace(/^[^\n]*\n\s?\d+.\s?/g,'');
opt=opt.replace(/\s?\n\s?\d+.\s?/g,',').split(',');
console.log(opt);

Upvotes: 1

Related Questions