문자 수로 문자열의 특정 부분 가져오기 (Take specific part of a string by character count)


문제 설명

문자 수로 문자열의 특정 부분 가져오기 (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 bboybeatleZakaria AcharkiZohaib IjazbeercoholLee Jenkins)

참조 문서

  1. Take specific part of a string by character count (CC BY‑SA 2.5/3.0/4.0)

#split #string #javascript






관련 질문

오류: 이 범위에서 '분할'이 선언되지 않았습니다. (error: ‘split’ was not declared in this scope)

화살표 문자가 포함된 문자열 분할 (Split a string containing arrow characters)

문자 수로 문자열의 특정 부분 가져오기 (Take specific part of a string by character count)

VBScript: 새로운 분할 항목이 있는 리조트 문자열 및 그룹 (VBScript: Resort String and group with new Split Item)

python 태그에서 단어와 숫자 나누기 (Split words and numbers from tags python)

구두점을 문자열 끝에서 시작 부분으로 이동하려면 어떻게 해야 합니까? (How can I move the punctuation from the end of a string to the beginning?)

쉼표로 문자열을 분할하지만 대괄호 또는 따옴표로 묶인 쉼표는 무시하십시오. (Split string by comma but ignore commas in brackets or in quotes)

숫자를 나누고 점 뒤에 하나의 숫자를 유지하십시오. (Split the number and keep one number after the dot)

Oracle에서 쉼표로 구분된 문자열의 최대 개수를 얻는 방법은 무엇입니까? (How to get maximum COUNT of comma separated string in Oracle?)

분할 방법을 사용하여 텍스트 파일에서 범주를 열로 분리 (Using the split method to separate categories into columns from a text file)

Powershell에서 문자열 분할 및 추가 (Splitting and Adding String in Powershell)

원래 문자열 포인터를 수정하지 않는 strtok_r() 및 strsep()에 대한 C-문자열 대안? (C-string alternatives to strtok_r() and strsep() that don't modify the original string pointer?)







코멘트