I have a string path1/path2
I need to get the values of path1
and path2
.
how can i do it?
And what about getting the same from such string http://www.somesite.com/#path1/path2
?
Thanks
Both are used to split a string into an array, but the difference is that split() uses pattern for splitting whereas explode() uses string. explode() is faster than split() because it doesn't match string based on regular expression.
Answer: Use the JavaScript split() method If you want to explode or split a string from a certain character or separator you can use the JavaScript split() method. The following example will show you how to split a string at each blank space. The returned value will be an array, containing the splitted values.
The explode() function breaks a string into an array. Note: The "separator" parameter cannot be an empty string. Note: This function is binary-safe.
The plain JavaScript String object has a split
method.
'path1/path2'.split('/')
'http://www.somesite.com/#path1/path2'.split('#').pop().split('/')
-> ['path1', 'path2']
However, for the second case, it's generally not a good idea to do your own URL parsing via string or regex hacking. URLs are more complicated than you think. If you have a location
object or an <a>
element, you can reliably pick the parts of the URL out of it using the protocol
, host
, port
, pathname
, search
and hash
properties.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With