我如何拆分一个string,打破一个特定的字符?
我有这个string
'john smith~123 Street~Apt 4~New York~NY~12345'
使用JavaScript,parsing这个最快的方法是什么?
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
你会想看看JavaScript的substr或split,因为这不是一个适合jQuery的任务
根据ECMAScript6 ES6
,干净的方式是破坏arrays:
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
那么最简单的方法就是这样的:
var address = theEncodedString.split(/~/) var name = address[0], street = address[1]
就像是:
var divided = str.split("/~/"); var name=divided[0]; var street = divided[1];
可能会是最简单的
如果分割器被发现,那么只有
拆分它
否则返回相同的string
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]; } } }
你可以使用split
来分割文本。
作为替代,您也可以使用match
如下
var str = 'john smith~123 Street~Apt 4~New York~NY~12345'; matches = str.match(/[^~]+/g); console.log(matches); document.write(matches);
扎克有一个正确的..使用他的方法,你也可以做一个看似“多维”数组..我创build了一个快速的例子在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(",");