comparing two string in for loop using if condition in javascript -
i working on javascript cookies , cookie name is
ssecname
want search cookie using code
function readcookie() { var allcookies = document.cookie; var cookiearray = allcookies.split(';'); for(var = 0; i<=cookiearray.length; i++) { name = cookiearray[i].split('=')[0]; coo_glo_value = cookiearray[i].split('=')[1]; alert(name); /* here shows name value equal ssecname not comparing below */ if(name == "ssecname") /* have tried === */ { alert('here go'); } } } i dont know why not comparing string when do
if(name != "ssecname") { alert('here go'); } so give me output here go cant understand why happening?? please me , kindly tell other way compare.. tahnks in advance :)
try use foreach:
function readcookie() { var cookies = document.cookie; var cookiebundle = cookies.split(';'); for(var in cookies) { var name = cookiebundle[i].split('=')[0], cookievalue = cookiebundle[i].split('=')[1]; if(name.trim() == "csrftoken") { alert("here go."); } } } readcookie(); you can play on jsfiddle.
(note: change cookie name in comparison).
to knowledge
a foreach works similar normal for. iterates on enumerable properties of object, in arbitrary order. each distinct property, statements can executed. (to more function, click here.)
the trim() function used based on botis' answer — removes empty spaces string.
Comments
Post a Comment