David Hope
David Hope

Reputation: 1546

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.

Upvotes: 8

Views: 12644

Answers (3)

baao
baao

Reputation: 73291

I'd use a simple replace..

var s = "mycool://?string=mysite.com/username_here80";
var ss = s.replace("mycool://?string=", "");
alert(ss);

Upvotes: 1

Dekel
Dekel

Reputation: 62676

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));

Upvotes: 4

Ted Hopp
Ted Hopp

Reputation: 234857

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.

Upvotes: 7

Related Questions