So I'm trying to split a string in javacript, something that looks like this:
"foo","super,foo"
Now, if I use .split(",")
it will turn the string into an array containing [0]"foo" [1]"super [2]foo"
however, I only want to split a ma that is between quotes, and if I use .split('","')
, it will turn into [0]"foo [1]super,foo"
Is there a way I can split an element expressing delimiters, but have it keep certain delimiters WITHOUT having to write code to concatenate a value back onto the string?
EDIT:
I'm looking to get [0]"foo",[1]"super,foo"
as my result. Essentially, the way I need to edit certain data, I need what is in [0] to never get changed, but the contents of [1] will get changed depending on what it contains. It will get concatenated back to look like "foo", "I WAS CHANGED"
or it will indeed stay the same if the contents of [1] where not something that required a change
So I'm trying to split a string in javacript, something that looks like this:
"foo","super,foo"
Now, if I use .split(",")
it will turn the string into an array containing [0]"foo" [1]"super [2]foo"
however, I only want to split a ma that is between quotes, and if I use .split('","')
, it will turn into [0]"foo [1]super,foo"
Is there a way I can split an element expressing delimiters, but have it keep certain delimiters WITHOUT having to write code to concatenate a value back onto the string?
EDIT:
I'm looking to get [0]"foo",[1]"super,foo"
as my result. Essentially, the way I need to edit certain data, I need what is in [0] to never get changed, but the contents of [1] will get changed depending on what it contains. It will get concatenated back to look like "foo", "I WAS CHANGED"
or it will indeed stay the same if the contents of [1] where not something that required a change
-
What's the final result you want from
"foo","super,foo"
? – Student Commented Mar 30, 2011 at 17:40 - Yes, thanks for the reminder to add it, Tom – James Commented Mar 30, 2011 at 17:43
- sorry, you want the output the same as the input? – Student Commented Mar 30, 2011 at 17:44
2 Answers
Reset to default 5Try this:
'"foo","super,foo"'.replace('","', '"",""').split('","');
For the sake of discussion and benefit of everyone finding this page is search of help, here is a more flexible solution:
var text = '"foo","super,foo"';
console.log(text.match(/"[^"]+"/g));
outputs
['"foo"', '"super,foo"']
This works by passing the 'g' (global) flag to the RegExp instance causing match to return an array of all occurrences of /"[^"]"/
which catches "foo,bar"
, "foo"
, and even "['foo', 'bar']"
("["foo", "bar"]"
returns [""["", "", "", ""]""]
.)
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745388286a4625541.html
评论列表(0条)