2017-10-13 5 views
0

문자열을 특정 문자 (예 : '/')로 분리하고 싶지만 안정적으로 기대할 수있는 '/'문자가 무엇인지 직접 알아야합니다. 그 캐릭터의 앞쪽은 그 캐릭터 앞 공간까지 있습니다.Javascript에서 알려진 문자 1 개와 알 수없는 문자 1 개가 포함 된 문자열 분할

예를 들어

:

이 myStr이 = "bob u/ used cars nr/ no resale value i/ information is attached to the vehicle tag bb/ Joe's wrecker service"

그래서, 나는 '/'로 분할 할 수 있도록 이미

mySplitStr = myStr.split('/');

를 사용하지만 지금 mySplitStr는

같은 배열입니다

mySplitStr[1] = "bob u" mySplitStr[2] = " used cars nr" mySplitStr[3] = " no resale value i"

그러나 '/'문자 바로 앞에있는 문자를 알아야합니다.

u nr i

은 내가 '/'다음의 정보로 무엇을 알 수 있도록하는 것이.

도움을 주시면 대단히 감사하겠습니다.

+0

흠, 어쩌면 수 charAt "/"다음 사용에 인덱스를 찾을 : 당신이 알고 싶은 전자, 그리고 당신이 그것을 잡아 수 있습니다 : 첫 번째 반복의 루프 내부

let mySplitStr = myStr.split('/'); for(let i = 0; i < mySplitStr.length; i++) { let mySplitStrEl = mySplitStr[i].split(" "); // Split current text element let lastCharsSet = mySplitStrEl[mySplitStrEl.length -1]; // Grab its last set of characters let myCurrentStr = mySplitStrEl.splice(mySplitStrEl.length -1, 1); // Remove last set of characters from text element myCurrentStr = mySplitStrEl.join(" "); // Join text element back into a string switch(lastCharsSet) { case "u": // Your code here case "nr": // Your code here case "i": // Your code here } } 

, "/"- 1). 그것은 당신이 찾고있는 것입니까? "/"앞에있는 캐릭터를 찾는 방법? –

답변

4

당신은 split이 정규 표현식 인수를 사용할 수 있습니다

let parts = myStr.split(/\s*(\S+)\/\s*/); 

지금 당신이 결과 배열의 모든 홀수 위치에있는 특수 문자를해야합니다. 당신이 당신의 문자열을 분할

let myStr = "bob u/ used cars nr/ no resale value i/ information is attached to the vehicle tag bb/ Joe's wrecker service"; 
 
let obj = myStr.split(/\s*(\S+)\/\s*/).reduceRight((acc, v) => { 
 
    if (acc.default === undefined) { 
 
     acc.default = v; 
 
    } else { 
 
     acc[v] = acc.default; 
 
     acc.default = undefined; 
 
    } 
 
    return acc; 
 
}, {}); 
 
console.log(obj);

+0

"bob", "u", "used cars"...가 아닌'u ','nr ','i 'etc' 등의 목록을 생성해야합니다. 이것은 내가 개인적으로 정규 표현식에서 벗어나는 이유입니다. 그들은 어렵습니다. –

+0

@IgorSoloydenko, ...OP는 * "계속되는 정보를 어떻게 처리해야 할지를 알기 위해 *"계속해서 말합니다. "*. 따라서 상황이 필요합니다. 이 질문의 해석의 차이점은 정규 표현식과는 아무런 관련이 없습니다. – trincot

+0

그 라인을 보았지만 요구 사항은 잘 모릅니다. 입력이 제공되지만 정확한 출력은 제공되지 않습니다. 적어도, 너와 나는 그것을 다르게 해석하고있다. –

0

나는 이것이 당신이 찾고있는 무엇을 생각 : '/'에 의해

"bob u/ used cars nr/ no resale value i/ information is attached to the vehicle tag bb/ Joe's wrecker service" 
    .split('/') 
    .map(splitPart => { 
    const wordsInPart = splitPart.split(' '); 
    return wordsInPart[wordsInPart.length - 1]; 
    }); 

// Produces: ["u", "nr", "i", "bb", "service"] 

분할이 충분하지 않습니다. 또한 분할 결과의 모든 부분을 방문하여 마지막 결과를 추출해야합니다.

0

후 :

let myStr = "bob u/ used cars nr/ no resale value i/ information is attached to the vehicle tag bb/ Joe's wrecker service"; 
 
let parts = myStr.split(/\s*(\S+)\/\s*/); 
 

 
console.log(parts);
.as-console-wrapper { max-height: 100% !important; top: 0; }

더 구조화 된 결과를 들어, 객체의 키로서 이러한 특수 문자 조합을 사용할 수 있습니다 , 실제로 배열을 얻습니다. 여기서 마지막 문자 세트는 on입니다. (인덱스

// lastCharsSet is "u" 
// myCurrentStr is "bob"