What is wrong with string compare in my javascript code?
I have different xml's (for diff os),开发者_StackOverflow I am posting only relevant xml part for SunOs xml.
<osname>SunOS
</osname>
This is fetched by jQuery
var osname = $(this).find('osname').text();
Later in the code when I compare, it always goes in to else
part, I used console.info
for firebug and attached a screenshot of my output
console.info("Before checking:"+osname);
if(osname=="HP-UX")
console.info("HP-UX");
else if(osname=="AIX")
console.info("AIX");
else if(osname=="SunOS")
console.info("SunOS");
else
{
console.info("Linux -");
}
Screenshot of Firebug console.info
My question is why can't it check for SunOs
or any other?
Note: I think there is a extra character after the osname, I also made a xsl
in that when I check i do something like below, how can i do it in JS?
XSL code
<xsl:if test="$sunos='SunOS
'">
I have also tried if(osname=="SunOS
")
That's because the string is not actually SunOS
, but SunOS\n
(where \n
stands for a newline). Use jQuery.trim
to remove the surrounding spaces.
var osname = $.trim($(this).find('osname').text());
May be you've got extraneous white space characters, try this
var osname = $.trim($(this).find('osname').text());
and compare using this osname. Check $.trim
for more details.
There may be a lot of white-spaces appended to your osname
-variable - I experience that quite often when using XML. Try checking on osname.trim()
.
It's probably because you get a line break at the end of the string, as the end tag is on the next line.
You can use the trim
method to remove whitespace character around the string:
var osname = $.trim($(this).find('osname').text());
console.info("Before checking:"+osname);
switch (osname) {
case "HP-UX":
console.info("HP-UX");
break;
case "AIX":
console.info("AIX");
break;
case "SunOS":
console.info("SunOS");
break;
default:
console.info("Linux -");
break;
}
精彩评论