I'm trying to get everything after certain characters in a string.
But I have no idea why with my, when I alert(); the result, there is a comma before the string!
Here is a working FIDDLE
And this is my code:
var url = "mycool://?string=mysite.com/username_here80";
var urlsplit = url.split("mycool://?string=");
alert(urlsplit);
any help would be appreciated.
Split separates the string into tokens separated by the delimiter. It always returns an array one longer than the number of tokens in the string. If there is one delimiter, there are two tokens—one to the left and one to the right. In your case, the token to the left is the empty string, so split()
returns the array ["", "mysite.com/username_here80"]
. Try using
var urlsplit = url.split("mycool://?string=")[1]; // <= Note the [1]!
to retrieve the second string in the array (which is what you are interested in).
The reason you are getting a comma is that converting an array to a string (which is what alert()
does) results in a comma-separated list of the array elements converted to strings.
The split
function of the string
object returns an Array of elements, based on the splitter. In your case - the returned 2 elements:
var url = "http://DOMAIN.com/username_here801";
var urlsplit = url.split("//");
console.log(urlsplit);
The comma you see is only the representation of the Array as string.
If you are looking for to get everything after a substring you better use the indexOf
and slice
:
var url = "http://DOMAIN.com/username_here801";
var splitter = '//'
var indexOf = url.indexOf(splitter);
console.log(url.slice(indexOf+splitter.length));
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