What does split function look like? - javascript

I came across this statement :
userName = document.cookie.split("=")[1];
after reading about split statement here at w3schools. which says that syntax of split is
string.split(separator, limit). Then what does the square bracket after first parens. mean ?
If this is true what does split function look like ?

String.split(separator, limit) returns an array. In Javascript, you can access array values by index using the square brackets. Arrays are zero-based, 0 is the first element, 1 the second and so on.
The equivalent of your code would be:
var arr = document.cookie.split("=");
userName = arr[1];
This separates the document.cookie by the equal-sign (=) and takes the second element (index 1) from it. document.cookie is a special property (datatype: String) of the document object which contains all cookies of a webpage, separated by the ; character. E.g. if document.cookie contains name=Adam, the array arr will contain the values name and Adam. The second one is stored in userName.
Note that if the cookie contains multiple values, or if the value contains multiple equal-signs, it won't work. Consider the next cases:
document.cookie contains name=Adam; home=Nowhere. Using the above code, this would make userName contain Adam; home because the string is separated by the equal-sign, and then the second value is taken.
document.cookie contains home=Nowhere; name=Adam. This would result in userName containing Nowhere; name
document.cookie contains name=Adam=cool. In this case, userName would be Adam and not Adam=cool.
Also, w3schools is not that reliable. Use more authorative sources like the Mozilla Developer Network:
document.cookie
String.split
Array

The split function returns an array of strings split by the given separator. With the square bracket you are accessing the nth element of that (returned) array.
If you are familiar with Java, its the same behavior as the String.split() method there.

It gets the second index of the resulting array
Same as:
var split = document.cookie.split("=");
var userName = split[1];

split returns an array of strings. So square brackets mean get second string from the returned array.

The square bracket in the code you supplied is accessing the second element of the array returned by split(). The function itself returns an array. That code would be the same as:
var temp = document.cookie.split("=");
userName = temp[1];

Split would return an array e.g. [1, 2, 3]. If you supply the square bracket after it, it will return the specified key in the brackets, in this case userName would be 2

You shouldn't be using w3schools, but...
In JavaScript, function parameters are optional and it is possible to supply fewer parameters than the function expects. The extra parameters in the function are then undefined. Some functions are programmed to deal with that possibility and string.split is one of them.
The other part has to do with the fact that split returns an array. Arrays can then be indexed using the square bracket notation, hence the [1] after the function call.

Related

Jquery data-target as string possible?

I have a data-attribute with a unique name and a number at the end.
data-target="foo-bar-n"
where n is the unique number.
I want to be able to get that number but it isn't working.
I call:
.data("target")
on the object I want the target from and It returns fine, but when I use a regex search on the results, I get a completely different number, which I suspect is because returned data is an object with other data. What I need to know is how to get that number out, or how to convert the data-attribute into a string. (I've tried toString, and that doesn't work.)
Here is my code:
var selection= window.getSelection().getRangeAt(0);
var showSelection = $(selection.commonAncestorContainer.parentNode.parentNode)
.data('target');
console.log(showSelection);
console.log(showSelection.search(/\d+/));
The console logs
#comment_for_paragraph_17
23
The program is meant to let a user select something on the page and highlight it.
If you are using jQuery 1.4.3 or later you can use
.data("target");
otherwise you must use
.attr("data-target");
But your requirement appears to be extracting a number from a formatted string parameter?
HTML:
<div id="foo" data-target="foo-bar-5"></div>
jQuery:
var num = $('#foo').data('target').split('-')[2];
Or regex:
var num = $('#foo').data('target').match(/\d+/);
Or if your requirement is specifically capture the last number in the string (eg: foo-bar-55-23 would result in '23')
var num = $('#foo').data('target').split('-').slice(-1);
// regex
var num = $('#foo').data('target').match(/\d+$/);
See fiddle
I suspect is because returned data is an object with other data.
That doesn't make any sense at all. The reason you are not getting the number in the string is because .search returns the index of the match. Use .match or .exec instead:
showSelection.match(/\d+/)[0];
/*or*/
/\d+/.exec(showSelection)[0];
Try:
.data('target').split('-').slice(-1)[0];
.split will split your string into an array with each array element being a word
.slice(-1) will return an array consisting of the last element of your array
[0] accesses the array element

get the matched data into array in javascript without using any loop

Problem background -- I want to get the nth root of the number where user can enter expression like "the nth root of x'.I have written a function nthroot(x,n) which return proper expected output.My problem is to extract the value of x and n from expression.
I want to extract some matched pattern and store it to a an array for further processing so that in next step i will pop two elements from array and replace the result in repression.But I am unable to get all the values into an array without using loop.
A perl equivalent of my code will be like below.
$str = "the 2th root of 4+678+the 4th root of -10000x90";
#arr = $str =~ /the ([-+]?\d+)th\s?root\s?of\s?([-+]?\d+)/g;
print "#arr";
I want the javascript equivalent of the above code.
or
any one line expression like below.
expr = expr.replace(/the\s?([+-]\d+)th\s?root\s?of([+-]\d+)/g,nthroot(\\$2,\\$1));
Please help me for the same.
The .replace() method that you are currently using is, as its name implies, used to do a string replacement, not to return the individual matches. It would make more sense to use the .match() method instead, but you can (mis)use .replace() if you use a callback function:
var result = expr.replace(/the\s?([+-]\d+)th\s?root\s?of([+-]\d+)/,function(m,m1,m2){
return nthroot(+m2, +m1);
});
Note that the arguments in the callback will be strings, so I'm converting them to numbers with the unary plus operator when passing them to your nthroot() function.
var regex=/the ([-+]?\d+)th\s?root\s?of\s?([-+]?\d+)/g;
expr=expr.replace(regex, replaceCallback);
var replaceCallback = function(match,p1,p2,offset, s) {
return nthroot(p2,p1);
//p1 and p2 are similar to $1 $2
}

How are strings physically stored in Javascript

What I am looking for is how strings are physically treated in Javascript. Best example I can think of for what I mean is that in the Java api it describes the storage of strings as:
String str = "abc";" is equivalent to: "char data[] = {'a', 'b', 'c'};
To me this says it uses an array object and stores each character as its own object to be used/accessed later (I am usually wrong on these things!)...
How does Javascript do this?
Strings are String objects in JavaScript. The String object can use the [] notation to get character from a string ("abc"[0] returns 'a'). You can also use the String.prototype.charAt function to achieve the same result.
Side node: var a = 'abc' and var b = new String('abc') are not the same. The first case is called a primitive string and get converted to a String object by the JavaScript parser. This results in other data types, calling typeof(a) gives you string but typeof(b) gives you object.
Strings are stored in the same format in javascript as other languages stores.
Suppose var word = "test" than at word will be as an array of characters and the 't' will come at 0th position and so on.
The last iteration as taking 'word.length' will return undefined. In other languages, it returns as '\0'.

String split returns an array with more elements than expected (empty elements)

I don't understand this behaviour:
var string = 'a,b,c,d,e:10.';
var array = string.split ('.');
I expect this:
console.log (array); // ['a,b,c,d,e:10']
console.log (array.length); // 1
but I get this:
console.log (array); // ['a,b,c,d,e:10', '']
console.log (array.length); // 2
Why two elements are returned instead of one? How does split work?
Is there another way to do this?
You could add a filter to exclude the empty string.
var string = 'a,b,c,d,e:10.';
var array = string.split ('.').filter(function(el) {return el.length != 0});
A slightly easier version of #xdazz version for excluding empty strings (using ES6 arrow function):
var array = string.split('.').filter(x => x);
This is the correct and expected behavior. Given that you've included the separator in the string, the split function (simplified) takes the part to the left of the separator ("a,b,c,d,e:10") as the first element and the part to the rest of the separator (an empty string) as the second element.
If you're really curious about how split() works, you can check out pages 148 and 149 of the ECMA spec (ECMA 262) at http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf
Use String.split() method with Array.filter() method.
var string = 'a,b,c,d,e:10.';
var array = string.split ('.').filter(item => item);
console.log(array); // [a,b,c,d,e:10]
console.log (array.length); // 1
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/split
trim the trailing period first
'a,b,c,d,e:10.'.replace(/\.$/g,''); // gives "a,b,c,d,e:10"
then split the string
var array = 'a,b,c,d,e:10.'.replace(/\.$/g,'').split('.');
console.log (array.length); // 1
That's because the string ends with the . character - the second item of the array is empty.
If the string won't contain . at all, you will have the desired one item array.
The split() method works like this as far as I can explain in simple words:
Look for the given string to split by in the given string. If not found, return one item array with the whole string.
If found, iterate over the given string taking the characters between each two occurrences of the string to split by.
In case the given string starts with the string to split by, the first item of the result array will be empty.
In case the given string ends with the string to split by, the last item of the result array will be empty.
It's explained more technically here, it's pretty much the same for all browsers.
According to MDN web docs:
Note: When the string is empty, split() returns an array containing
one empty string, rather than an empty array. If the string and
separator are both empty strings, an empty array is returned.
const myString = '';
const splits = myString.split();
console.log(splits);
// ↪ [""]
Well, split does what it is made to do, it splits your string. Just that the second part of the split is empty.
Because your string is composed of 2 part :
1 : a,b,c,d,e:10
2 : empty
If you try without the dot at the end :
var string = 'a,b,c:10';
var array = string.split ('.');
output is :
["a,b,c:10"]
You have a string with one "." in it and when you use string.split('.') you receive array containing first element with the string content before "." character and the second element with the content of the string after the "." - which is in this case empty string.
So, this behavior is normal. What did you want to achieve by using this string.split?
try this
javascript gives two arrays by split function, then
var Val = "abc#gmail.com";
var mail = Val.split('#');
if(mail[0] && mail[1]) { alert('valid'); }
else { alert('Enter valid email id'); valid=0; }
if both array contains length greater than 0 then condition will true

Regex to extract substring, returning 2 results for some reason

I need to do a lot of regex things in javascript but am having some issues with the syntax and I can't seem to find a definitive resource on this.. for some reason when I do:
var tesst = "afskfsd33j"
var test = tesst.match(/a(.*)j/);
alert (test)
it shows
"afskfsd33j, fskfsd33"
I'm not sure why its giving this output of original and the matched string, I am wondering how I can get it to just give the match (essentially extracting the part I want from the original string)
Thanks for any advice
match returns an array.
The default string representation of an array in JavaScript is the elements of the array separated by commas. In this case the desired result is in the second element of the array:
var tesst = "afskfsd33j"
var test = tesst.match(/a(.*)j/);
alert (test[1]);
Each group defined by parenthesis () is captured during processing and each captured group content is pushed into result array in same order as groups within pattern starts. See more on http://www.regular-expressions.info/brackets.html and http://www.regular-expressions.info/refcapture.html (choose right language to see supported features)
var source = "afskfsd33j"
var result = source.match(/a(.*)j/);
result: ["afskfsd33j", "fskfsd33"]
The reason why you received this exact result is following:
First value in array is the first found string which confirms the entire pattern. So it should definitely start with "a" followed by any number of any characters and ends with first "j" char after starting "a".
Second value in array is captured group defined by parenthesis. In your case group contain entire pattern match without content defined outside parenthesis, so exactly "fskfsd33".
If you want to get rid of second value in array you may define pattern like this:
/a(?:.*)j/
where "?:" means that group of chars which match the content in parenthesis will not be part of resulting array.
Other options might be in this simple case to write pattern without any group because it is not necessary to use group at all:
/a.*j/
If you want to just check whether source text matches the pattern and does not care about which text it found than you may try:
var result = /a.*j/.test(source);
The result should return then only true|false values. For more info see http://www.javascriptkit.com/javatutors/re3.shtml
I think your problem is that the match method is returning an array. The 0th item in the array is the original string, the 1st thru nth items correspond to the 1st through nth matched parenthesised items. Your "alert()" call is showing the entire array.
Just get rid of the parenthesis and that will give you an array with one element and:
Change this line
var test = tesst.match(/a(.*)j/);
To this
var test = tesst.match(/a.*j/);
If you add parenthesis the match() function will find two match for you one for whole expression and one for the expression inside the parenthesis
Also according to developer.mozilla.org docs :
If you only want the first match found, you might want to use
RegExp.exec() instead.
You can use the below code:
RegExp(/a.*j/).exec("afskfsd33j")
I've just had the same problem.
You only get the text twice in your result if you include a match group (in brackets) and the 'g' (global) modifier.
The first item always is the first result, normally OK when using match(reg) on a short string, however when using a construct like:
while ((result = reg.exec(string)) !== null){
console.log(result);
}
the results are a little different.
Try the following code:
var regEx = new RegExp('([0-9]+ (cat|fish))','g'), sampleString="1 cat and 2 fish";
var result = sample_string.match(regEx);
console.log(JSON.stringify(result));
// ["1 cat","2 fish"]
var reg = new RegExp('[0-9]+ (cat|fish)','g'), sampleString="1 cat and 2 fish";
while ((result = reg.exec(sampleString)) !== null) {
console.dir(JSON.stringify(result))
};
// '["1 cat","cat"]'
// '["2 fish","fish"]'
var reg = new RegExp('([0-9]+ (cat|fish))','g'), sampleString="1 cat and 2 fish";
while ((result = reg.exec(sampleString)) !== null){
console.dir(JSON.stringify(result))
};
// '["1 cat","1 cat","cat"]'
// '["2 fish","2 fish","fish"]'
(tested on recent V8 - Chrome, Node.js)
The best answer is currently a comment which I can't upvote, so credit to #Mic.

Categories

Resources