-
Split method
I have a string value that looks like this.
Code:
/about/company-names/
I want to try and separate the names from the slashes into an array so I have
Code:
var arr : Array = [about, company-names]
I tried the split function but it gives me added spaces with nothing in the array index.
example:
Code:
var str = '/about/company-names/';
var spl = str.split('/');
trace("spl = "+spl);
output : ,about,company-names,
How can I split it so I end up with this.
Code:
var arr : Array = [about, company-names]
-
Here's a hacky fix - throw this in before you split.
PHP Code:
while(str.substr(0,1) == '/'){ str = str.slice(1) };
while(str.substr(-1) == '/'){ str = str.slice(0, str.length - 1) };
-
Thanks neznein9 here is another hack fix I came up with.
Thanks again for the help
Code:
private function splitElements(str : String) : Array
{
var arr : Array = [];
var split = str.split('/');
for(var i:int = 0; i < split.length; i++){
if(split[i]){
arr.push(split[i]);
}
}
return arr;
}
I thought there might be a simpler way of doing this but I guess not.
-
-
Wow this works great and its only one line. I'm impressed. Can you explain what it does and how it works, loving it thanks
-
Code:
str.match(/[^\/]+/g)
Broken down:
str
The String you're performing the operation on (str being the name of the variable)
match
A method of the String class, match is kind of like a regular expression-enabled version of String.split(). It takes a regular expression and returns an array of strings represented the sub-strings in your original that matches the supplied expression
/[...]/g
This is shorthand for the regular expression being used. The contents within the "/" characters represent the pattern and trailing characters are flags. This regular expression uses the g flag which stands for "global" meaning it won't stop after the first match is found; it will keep searching until the end of the string is reached. Regular expressions can also be created with the RegExp class which accepts these parts separately within the constructor.
[^\/]+
This is the meat of the regular expression. It is pretty much one rule: Find everything that is at least one character that is not the "/" character. The brackets [] represent a group. Usually they mean "has everything in this", but they mean "has nothing in this" when the first character is a "^". You can see that almost as being the equivalent to ! for Boolean variables, but here, for [] groups. Next is \/, which represents the "/" character. The "\" is included to escape the "/". Otherwise it would indicate the end of the regular expression. Following the group is a + which means one or more of what preceeded it. Here, it means one or more non-/ characters.
The Flex/AS docs have more info on regular expressions and their syntax in AS
http://livedocs.adobe.com/flex/3/htm...ssions_03.html
and you can find even more docs online about reg exp in general