私はこの文字列を持っています
'john smith~123 Street~Apt 4~New York~NY~12345'
JavaScriptを使用して、これを解析する最速の方法は何ですか?
var name = "john smith";
var street= "123 Street";
//etc...
私はこの文字列を持っています
'john smith~123 Street~Apt 4~New York~NY~12345'
JavaScriptを使用して、これを解析する最速の方法は何ですか?
var name = "john smith";
var street= "123 Street";
//etc...
JavaScript の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];
これは最も簡単な方法ではありませんが、次のようにすることができます。
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
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 address = theEncodedString.split(/~/)
var name = address[0], street = address[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);
正規表現[^~]+
は、 を除くすべての文字~
に一致し、一致したものを配列で返します。その後、そこから一致を抽出できます。
何かのようなもの:
var divided = str.split("/~/");
var name=divided[0];
var street = divided[1];
おそらく最も簡単になるでしょう
ザックはこれを1つ正しく持っていました..彼の方法を使用すると、一見「多次元」配列を作成することもできます..私は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(",");