Reputation: 567
I want to take a user submitted string and use parts of it as different variables. I used this to split the text after every third letter...
var values = value.match(/.{3}|.{1,2}/g);
That gives me a nice array of the string split into 3s:
["658", "856", "878", "768", "677", "896"]
However I realised that isn't what I need. I actually need the first 2 letters (var 1), the next 3 letters (var 2), next 1 letter (var 3) etc. etc.
So I would be essentially splitting them more like this...
["65", "885", "6" .....
I don't really need an array as it will be one long number each time, It could look more like...
var Part1 = Number.(grab first 2 characters)
var Part2 = Number.(grab 3 characters from the 3rd onwards)
var Part3 = Number.(grab 6th character only)
etc.. if you can imagine thats properly coded. I can't find detailed information on the .match method.
Upvotes: 3
Views: 202
Reputation: 2470
Actually, you can use a regular expression to extract multiple substrings in a single call the the match
function. You just need to add parenthesis to your regular expression, like this:
var s = "1234567890";
var s.match(/([0-9]{3})([0-9]{1})([0-9]{2})([0-9]{3})/);
for( var i=0; i<matches.length; ++i ) {
console.log(matches[i]);
}
Output:
123456789
123
4
56
789
Notice that match
returns the entire match as element zero of the returned array. My example regex only extracts nine characters, so that's why there is no zero in the output.
IMHO Regular expressions are worth learning because they give you a powerful and concise way to perform string matching. They work (mostly) the same from one language to another, so you can apply the same knowledge in JavaScript, python, ruby, java, whatever.
For more information about regular expressions in JavaScript, see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
Upvotes: 0
Reputation: 22885
I hope this is what you are asking for
var value = "123456789123456789";
var values = [];
while(value.length){
[2, 3, 1].forEach(function(d){
values.push(value.substr(0,d));
value = value.substr(d);
})
}
This is the output:
values = ["12", "345", "6", "78", "912", "3", "45", "678", "9"]
but value
string will be ""
at the end of loop, so if you want to reuse it, make a copy of it.
Upvotes: 1
Reputation: 2587
As @Teemu above suggests, you can just use the substr()
or substring()
string methods.
For example:
var Part1 = value.substr(0, 2);
var Part2 = value.substr(2, 3);
var Part3 = value.substr(5, 1);
See a JS Fiddle example here: https://jsfiddle.net/xpuv4e5j/
Upvotes: 0
Reputation: 67505
You can use .substr()
instead of match()
:
// grab first 2 characters
"123456789".substr(0, 2); //return "12"
// grab 3 characters from the 3rd onwards
"123456789".substr(2, 3); //return "345"
// grab 6th character only
"123456789".substr(5, 1); //return "6"
Hope this helps.
Upvotes: 2