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 ma before the string!
Here is a working FIDDLE
And this is my code:
var url = "mycool://?string=mysite/username_here80";
var urlsplit = url.split("mycool://?string=");
alert(urlsplit);
any help would be appreciated.
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 ma before the string!
Here is a working FIDDLE
And this is my code:
var url = "mycool://?string=mysite./username_here80";
var urlsplit = url.split("mycool://?string=");
alert(urlsplit);
any help would be appreciated.
Share Improve this question asked Dec 4, 2016 at 15:45 David HopeDavid Hope 1,5364 gold badges26 silver badges54 bronze badges 2-
String#split returns exactly an
Array
(yes, a real instance ofArray
, thus a way to get the latest element is by using thelast
getter), soalert
stringifies this array of splits. – user5066707 Commented Dec 4, 2016 at 15:47 -
Do
url.split("=").pop()
instead. – trincot Commented Dec 4, 2016 at 15:49
3 Answers
Reset to default 7Split 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./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 ma is that converting an array to a string (which is what alert()
does) results in a ma-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./username_here801";
var urlsplit = url.split("//");
console.log(urlsplit);
The ma 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./username_here801";
var splitter = '//'
var indexOf = url.indexOf(splitter);
console.log(url.slice(indexOf+splitter.length));
I'd use a simple replace..
var s = "mycool://?string=mysite./username_here80";
var ss = s.replace("mycool://?string=", "");
alert(ss);