program story

자바 스크립트에서 문자열을 한 번 분할 하시겠습니까?

inputbox 2020. 10. 28. 08:04
반응형

자바 스크립트에서 문자열을 한 번 분할 하시겠습니까?


어떻게 한 번만 즉, 메이크업의 문자열을 분할 할 수 있습니다 1|Ceci n'est pas une pipe: | Oui에 구문 분석을 : ["1", "Ceci n'est pas une pipe: | Oui"]?

분할의 한계가 도움이되지 않는 것 같습니다 ...


이것은 예쁜 접근 방식은 아니지만 적절한 효율성으로 작동합니다.

var string = "1|Ceci n'est pas une pipe: | Oui";
var components = string.split('|');
alert([components.shift(), components.join('|')]​);​​​​​

여기에 대한 간단한 데모가 있습니다.


String.indexOf('|')'|'가 처음 나타나는 색인을 가져 오는 데 사용하고 싶을 것 입니다.

var i = s.indexOf('|');
var splits = [s.slice(0,i), s.slice(i+1)];

당신이 사용할 수있는:

var splits = str.match(/([^|]*)\|(.*)/);
splits.shift();

정규식은 문자열을 두 개의 일치하는 그룹 (괄호로 묶음)으로 분할하고 첫 번째 | 그리고 뒤에 텍스트. 그런 다음 shift전체 문자열 일치 ( splits[0])를 제거하는 결과 입니다.


하나의 라이너와 imo, 더 간단 :

var str = 'I | am super | cool | yea!';
str.split('|').slice(1).join('|');

이것은 "am super | cool | yea!"를 반환합니다.


이 시도:

function splitOnce(input, splitBy) {
    var fullSplit = input.split(splitBy);
    var retVal = [];
    retVal.push( fullSplit.shift() );
    retVal.push( fullSplit.join( splitBy ) );
    return retVal;
}

var whatever = splitOnce("1|Ceci n'est pas une pipe: | Oui", '|');

문자열에 구분 기호가 포함되지 않은 경우 @NickCraver의 솔루션은 여전히 ​​두 요소의 배열을 반환하고 두 번째 요소는 빈 문자열입니다. 나는 분할과 일치하는 행동을 선호합니다. 즉, 입력 문자열에 구분 기호가 포함되어 있지 않으면 단일 요소가있는 배열 만 반환됩니다.

var splitOnce = function(str, delim) {
    var components = str.split(delim);
    var result = [components.shift()];
    if(components.length) {
        result.push(components.join(delim));
    }
    return result;
};

splitOnce("a b c d", " "); // ["a", "b c d"]
splitOnce("a", " "); // ["a"]

지금까지 대부분의 답변만큼이나 악합니다.

var splits = str.split('|');
splits.splice(1, splits.length - 1, splits.slice(1).join('|'));

ES6 구문은 다른 접근 방식을 허용합니다.

function splitOnce(s, on) {
   [first, ...rest] = s.split(on)
   return [first, rest.length > 0? rest.join(on) : null]
}

또한 |빈 문자열이 아닌 null을 반환 하여 문자열이없는 결과를 처리합니다 .

splitOnce("1|Ceci n'est pas une pipe: | Oui", "|")
>>> ["1", "Ceci n'est pas une pipe: | Oui"]

splitOnce("Celui-ci n'a pas de pipe symbol!", "|")
>>> ["Celui-ci n'a pas de pipe symbol!", null]

파 드 파이프? C'est null!

나는 주로 파이프 기호에 말장난을 할 수 있도록이 답장을 추가했지만, es6 구문을 보여주기 위해-얼마나 ​​많은 사람들이 여전히 그것을 사용하지 않는지 놀랍습니다.


다른 곳의 상품 외에 다른 짧은 접근 방식은 replace()의 한계를 활용하는 것입니다.

var str = "1|Ceci n'est pas une pipe: | Oui";
str.replace("|", "aUniquePhraseToSaySplitMe").split("aUniquePhraseToSaySplitMe");

As @sreservoir points out in the comments, the unique phrase must be truly unique--it cannot be in the source you're running this split over, or you'll get the string split into more pieces than you want. An unprintable character, as he says, may do if you're running this against user input (i.e., typed in a browser).


This one's a little longer, but it works like I believe limit should:

function split_limit(inString, separator, limit){
    var ary = inString.split(separator);
    var aryOut = ary.slice(0, limit - 1);
    if(ary[limit - 1]){
        aryOut.push(ary.slice(limit - 1).join(separator));
    }
    return aryOut;
}
console.log(split_limit("1|Ceci n'est pas une pipe: | Oui","|", 1));
console.log(split_limit("1|Ceci n'est pas une pipe: | Oui","|", 2));
console.log(split_limit("1|Ceci n'est pas une pipe: | Oui","|", 3));
console.log(split_limit("1|Ceci n'est pas une pipe: | Oui","|", 7));

https://jsfiddle.net/2gyxuo2j/

limit of Zero returns funny results, but in the name of efficiency, I left out the check for it. You can add this as the first line of the function if you need it:

if(limit < 1) return [];

use the javascript regular expression functionality and take the first captured expression.

the RE would probably look like /^([^|]*)\|/.

actually, you only need /[^|]*/ if you validated that the string is formatted in such a way, due to javascript regex greediness.

참고URL : https://stackoverflow.com/questions/2878703/split-string-once-in-javascript

반응형