Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: get everything after certain characters from a string?

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.

like image 944
David Hope Avatar asked Mar 11 '23 12:03

David Hope


2 Answers

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.

like image 97
Ted Hopp Avatar answered Mar 13 '23 03:03

Ted Hopp


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));
like image 32
Dekel Avatar answered Mar 13 '23 03:03

Dekel