문제

이 문자열

'john smith~123 Street~Apt 4~New York~NY~12345'

자바스크립트를 사용하여 가장 빠른 방법은 무엇입을 분석하이로

var name = "john smith";
var street= "123 Street";
//etc...
도움이 되었습니까?

해결책

자바 스크립트의 String.prototype.split 기능:

var input = 'john smith~123 Street~Apt 4~New York~NY~12345';

var fields = input.split('~');

var name = fields[0];
var street = fields[1];
// etc.

다른 팁

당신이 필요하지 않 jQuery.

var s = 'john smith~123 Street~Apt 4~New York~NY~12345';
var fields = s.split(/~/);
var name = fields[0];
var street = fields[1];

에 따라 ECMAScript6 ES6, 고,청소하는 방법입니다 파멸의 배열:

const input = 'john smith~123 Street~Apt 4~New York~NY~12345';

const [name, street, unit, city, state, zip] = input.split('~');

console.log(name); // john smith
console.log(street); // 123 Street
console.log(unit); // Apt 4
console.log(city); // New York
console.log(state); // NY
console.log(zip); // 12345

할 수 있습에 추가 항목에 입력된 문자열입니다.이 경우에,당신은 나머지 부분을 사용할 수 있습니다 운영자를 배열을 얻을 나머지를 위해 또는 그냥 그들을 무시한다:

const input = 'john smith~123 Street~Apt 4~New York~NY~12345';

const [name, street, ...others] = input.split('~');

console.log(name); // john smith
console.log(street); // 123 Street
console.log(others); // ["Apt 4", "New York", "NY", "12345"]

저는 읽기 전용 참조를 위해 가치와 사용 const 선언입니다.

을 즐길 수 있 ES6!

비록 이것은 가장 간단한 방법으로,당신은 이렇게 할 수 있다:

var addressString = "~john smith~123 Street~Apt 4~New York~NY~12345~",
    keys = "name address1 address2 city state zipcode".split(" "),
    address = {};

// clean up the string with the first replace
// "abuse" the second replace to map the keys to the matches
addressString.replace(/^~|~$/g).replace(/[^~]+/g, function(match){
    address[ keys.unshift() ] = match;
});

// address will contain the mapped result
address = {
    address1: "123 Street"
    address2: "Apt 4"
    city: "New York"
    name: "john smith"
    state: "NY"
    zipcode: "12345"
}

업데이트에 대한 ES2015 사용하여 선언 및

const [address1, address2, city, name, state, zipcode] = addressString.match(/[^~]+/g);

// The variables defined above now contain the appropriate information:

console.log(address1, address2, city, name, state, zipcode);
// -> john smith 123 Street Apt 4 New York NY 12345

당신이 보길 원하는 자바 스크립트의 substr분할, 으로,이것은 정말 작업에 적합한 jQuery.

론,가장 쉬운 방법은 다음과 같습니다.

var address = theEncodedString.split(/~/)
var name = address[0], street = address[1]

는 경우 Spliter 이 발견

분할

다른 반환 동일한 문자열

function SplitTheString(ResultStr) {
    if (ResultStr != null) {
        var SplitChars = '~';
        if (ResultStr.indexOf(SplitChars) >= 0) {
            var DtlStr = ResultStr.split(SplitChars);
            var name  = DtlStr[0];
            var street = DtlStr[1];
        }
    }
}

다음과 같습니다.

var divided = str.split("/~/");
var name=divided[0];
var street = divided[1];

아마가 될 것이 쉽

당신이 사용할 수 있는 split 텍스트를 분할.

에 대한 대안으로 사용할 수도 있습니다 match 으로 따르

var str = 'john smith~123 Street~Apt 4~New York~NY~12345';
matches = str.match(/[^~]+/g);

console.log(matches);
document.write(matches);

Regex [^~]+ 맞 모든 문자는 제외 ~ 고 돌아 경기 훌륭한 기능들을 가지고 있습니다.할 수 있는 다음 추출과 일치하다.

Zach 이 하나의 오른쪽..자신의 방법을 사용하여할 수 있도 겉으로는"다차원"배열..내가 만들어 간단한 예제에서 JSFiddle http://jsfiddle.net/LcnvJ/2/

// array[0][0] will produce brian
// array[0][1] will produce james

// array[1][0] will produce kevin
// array[1][1] will produce haley

var array = [];
    array[0] = "brian,james,doug".split(",");
    array[1] = "kevin,haley,steph".split(",");

string.split("~")[0]; 을 가져옵니다.

출처: 문자열입니다.프로토 타입입니다.split()


다른 기능적인 접근 방식을 사용하여 카레 및 기능분입니다.

그래서 먼저 될 것이 분리 기능입니다.이것을 만들고 싶 "john smith~123 Street~Apt 4~New York~NY~12345"["john smith", "123 Street", "Apt 4", "New York", "NY", "12345"]

const split = (separator) => (text) => text.split(separator);
const splitByTilde = split('~');

그래서 지금 우리가 사용할 수 있습니다 우리의 전문 splitByTilde 기능입니다.예제:

splitByTilde("john smith~123 Street~Apt 4~New York~NY~12345") // ["john smith", "123 Street", "Apt 4", "New York", "NY", "12345"]

첫 번째 요소를 사용할 수 있습니다 list[0] 연산자입니다.Let's build a first 기능:

const first = (list) => list[0];

이 알고리즘은 다음과 같습니다분할에 콜론 다음의 첫 번째 요소는 주어진 목록입니다.그래서 우리는 작성할 수 있습니다 그리고 그 기능을 구축하는 우리의 최종 getName 기능입니다.건설 compose 기능 reduce:

const compose = (...fns) => (value) => fns.reduceRight((acc, fn) => fn(acc), value);

그리고 지금 그것을 사용하여 작성 splitByTildefirst 기능입니다.

const getName = compose(first, splitByTilde);

let string = 'john smith~123 Street~Apt 4~New York~NY~12345';
getName(string); // "john smith"

이후로 나누는 쉼표에서 질문에 중복하여 이 질문을 추가,신것을 환영합니다.

하고 싶은 경우에 분할 문자와 처리하고 있는 추가 공백을 수행 할 수 있습는 문자,수시로 일어나는 쉼표로 사용할 수 있습니다 replace 다음 split, 은 다음과 같습니다.

var items = string.replace(/,\s+/, ",").split(',')

시에서 일반 자바 스크립트

 //basic url=http://localhost:58227/ExternalApproval.html?Status=1

 var ar= [url,statu] = window.location.href.split("=");

이 코드를 사용하여--

function myFunction() {
var str = "How are you doing today?";
var res = str.split("/");

}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top