How do I split a string, breaking at a particular character?

青春壹個敷衍的年華 提交于 2019-11-25 21:40:34

问题


I have this string

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

Using JavaScript, what is the fastest way to parse this into

var name = \"john smith\";
var street= \"123 Street\";
//etc...

回答1:


With JavaScript’s String.prototype.split function:

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.



回答2:


You don't need 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];



回答3:


According to ECMAScript6 ES6, the clean way is destructing 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

You may have extra items in the input string. In this case, you can use rest operator to get an array for the rest or just ignore them:

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"]

I supposed a read-only reference for values and used the const declaration.

Enjoy ES6!




回答4:


Even though this is not the simplest way, you could do this:

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"
}

Update for ES2015, using destructuring

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



回答5:


You'll want to look into JavaScript's substr or split, as this is not really a task suited for jQuery.




回答6:


well, easiest way would be something like:

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



回答7:


If Spliter is found then only

Split it

else return the same 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];
        }
    }
}



回答8:


Something like:

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

Is probably going to be easiest




回答9:


You can use split to split the text.

As an alternative, you can also use match as follow

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

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

The regex [^~]+ will match all the characters except ~ and return the matches in an array. You can then extract the matches from it.




回答10:


Zach had this one right.. using his method you could also make a seemingly "multi-dimensional" array.. I created a quick example at 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(",");



回答11:


This string.split("~")[0]; gets things done.

source: String.prototype.split()


Another functional approach using curry and function composition.

So the first thing would be the split function. We want to make this "john smith~123 Street~Apt 4~New York~NY~12345" into this ["john smith", "123 Street", "Apt 4", "New York", "NY", "12345"]

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

So now we can use our specialized splitByTilde function. Example:

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

To get the first element we can use the list[0] operator. Let's build a first function:

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

The algorithm is: split by the colon and then get the first element of the given list. So we can compose those functions to build our final getName function. Building a compose function with reduce:

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

And now using it to compose splitByTilde and first functions.

const getName = compose(first, splitByTilde);

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



回答12:


Try in Plain Javascript

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

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



回答13:


Since the splitting on commas question is duplicated to this question, adding this here.

If you want to split on a character and also handle extra whitespace that might follow that character, which often happens with commas, you can use replace then split, like this:

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



回答14:


Use this code --

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

}



回答15:


JavaScript: Convert String to Array JavaScript Split

    var str = "This-javascript-tutorial-string-split-method-examples-tutsmake."
 
    var result = str.split('-'); 
     
    console.log(result);
     
    document.getElementById("show").innerHTML = result; 
<html>
<head>
<title>How do you split a string, breaking at a particular character in javascript?</title>
</head>
<body>
 
<p id="show"></p> 
 
</body>
</html>

https://www.tutsmake.com/javascript-convert-string-to-array-javascript/



来源:https://stackoverflow.com/questions/96428/how-do-i-split-a-string-breaking-at-a-particular-character

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!