문제 설명
문자 수로 문자열의 특정 부분 가져오기 (Take specific part of a string by character count)
사용자가 제출한 문자열을 가져와서 그 일부를 다른 변수로 사용하고 싶습니다. 저는 이것을 사용하여 세 번째 문자마다 텍스트를 분할했습니다...
var values = value.match(/.{3}|.{1,2}/g);
3으로 분할된 문자열의 멋진 배열을 제공합니다.
["658", "856", "878", "768", "677", "896"]
하지만 그게 아니라는 것을 깨달았습니다. 내가 필요한 것. 나는 실제로 처음 2글자(var 1), 다음 3글자(var 2), 다음 1글자(var 3) 등이 필요합니다.
그래서 저는 본질적으로 이것을 더 많이 분할할 것입니다. ..
["65", "885", "6" .....
배열은 매번 긴 숫자이므로 필요하지 않습니다. 다음과 같이 보일 수 있습니다.
var Part1 = Number.(grab first 2 characters)
var Part2 = Number.(grab 3 characters from the 3rd onwards)
var Part3 = Number.(grab 6th character only)
등.. 가능하다면 제대로 코딩되었다고 상상해보십시오. .match 메소드에 대한 자세한 정보를 찾을 수 없습니다.
참조 솔루션
방법 1:
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.
방법 2:
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.
방법 3:
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/
방법 4:
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
(by bboybeatle、Zakaria Acharki、Zohaib Ijaz、beercohol、Lee Jenkins)