Cannot compare String returned by out.print() - javascript

I am using jsp as a server side script with HTML/JQuery for the client end.
I am doing a AJAX to the jsp file and everything works ok.
The problem starts when I am trying to compare the string returned by out.print() from jsp with in the jquery ajax result. The comparison never seems to result true!
It seems the out.print() is prepending a number of /n to the string.
$.post("jsp/login.jsp", { msg: $email.val() + "~" + $pass.val() }, function (result) {
if (result === "OK")
alert("Logged in");
else
alert("Invalid Credentials");
});

It seems the out.print() is prepending a number of /n to the string.
In this case you have two options. First, you can remove the extra whitespace in JS before using the value in a condition:
if ($.trim(result) === "OK")
alert("Logged in");
else
alert("Invalid Credentials");
Alternatively, and preferably, you could change your JSP code to return JSON. By definition this cannot have extraneous whitespace added to the values of its properties.

Remember how Java object comparisons work. In java a string literal "OK" in this case is itself an object and has it's own location in memory. When you do a comparison with another string object, result in this case, you aren't comparing the actual value of the two strings as you would with primitive types you're comparing the object location in memory. As such, you could use something like compareTo which is associated with String, something like this.
//Compare to returns an int, -1 for less then, 1 for greater then and 0 for equals
if(result.compareTo("OK") == 0){
//Do your code here
}

Related

identifying numbers using javascript

How can I make a function that takes a string and checks if it is a number string or if it includes letters/other characters? I have no idea what to do... RegExp takes too long so is there another way?
You have to use isNaN() function (is Not a Number). It will return you true if it's not a number (that mean that it contains letter) and false if it's one.
Source :
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/isNaN
You can check for isNaN and see if value is number if you don't want to go with RegExp.
let inpArgs = Number.parseInt(input);
if(!Number.isNaN(inpArgs)){
// this check ensures that your input is number
// Do what you have to do
}
else{
// Handle the error
}
But I would prefer the one line check using RegExp any day like below.
if(/^\d+$/.test(Number(input))){
// this says your input is Number
}
You can use typeof oprator to check whether it is a number or string.
function(anything){
if(typeof(anything)==='number'){ //do something} }
if(typeof(anything)==='string'){ //do something} }
Hope I answer your question.
Thanks.
You can use typeof in JavaScript to identify input Like
alert(typeof <your input>); or var identity = typeof <your input>;
and whatever string alert that match in Condition Like
if (identity == <alert message>){do something}else{do something}

How to compare string variable using JavaScript

I am trying to compare the variable using javascipt:
response value: ""test#gmail.com""
response value i am getting it from server.
var str1="test#gmail.com"
var str2 =response;
if(str1===str2)
{
//
}
However not getting the proper result.
any idea on how to compare them ?
There are a few ways to achieve your goal:
1) You can remove all " from the response when doing your equality check:
if(str1===str2.replace(/['"]+/g, ''))
{
//
}
2) Change your server code to not include ". Doing so, would mean that your Javascript will not need to change.
3) Last option, add " to your str1:
var str1='"test#gmail.com"'
var str2 =response;
if(str1===str2)
{
//
}
Obviously I don't know enough about your requirements to tell you which one you should do, but my suggestion would be choice #2 because I think it's strange to return an email address wrapped in quotes, otherwise I would recommend #1.
You are trying to compare '""test#gmail.com""' with 'test#gmail.com'. They would never be equal.
Actually ""test#gmail.com"" is not a valid string. It might have been represented as '""test#gmail.com""' and "test#gmail.com" is a valid string (Same as 'test#gmail.com').

If path contains directory

I want to trigger a digital marketing tag on every page which falls under a particular URL path, say example.com/sachin under the sachin directory.
I've tried if (location.href === 'example.com/sachin.*/') but somehow the condition doesn't seem to work.
What will be the correct if condition for location.href if I want to cover all different resources with in the URL path say under sachin directory?
I presume you want to check if the URL contains example.com/sachin. It's highly rarely that any URL ever would contain 4 forward-slashes but what you would do is utilize indexOf.
if(location.href.indexOf("example.com/sachin/") != -1){
//Do something
}
This basically says, if "example.com/sachin/" is found somewhere in the given string(in location.href in this case) on an indexposition that is not -1(which means that it doesn't exist), then execute.
You need to use Regular Expressions to match needed resources.
Something like that:
if(location.href.match(/^http:\/\/example.com\/sachin\//)){
//your staff here
}
Another approach to check for a specific directory in a url.
function urlContains(url, value) {
return ~url.indexOf(value);
}
if (urlContains(location.href, "/sachin/")) {
// found
} else {
// not found
}
The indexOf method checks a string for the value that is passed and returns -1 if a result was not found.
Instead of checking for == -1 or != -1 you can use the Bitwise NOT operator ~ to convert -1 to 0, which is a falsy value, non-zero values are treated are truthy values in javascript.

Comparing el.text() === "string" results in false, even when element contains "string"

In the below code, the else and not the if is always executed even though the alert tells me that state does in fact contain the string payment.
var state = $('.check-state').text();
alert(state); // payment
if (state === "payment")
alert('hello');
else
alert('not match')
Why is that?
I am guessing your HTML look sort of like this:
<div class="check-state">
payment
</div>
Then the .text() will return everything between the > and the <, including the whitespace. So what you get is "\n payment\n", not "payment".
The solution is to trim the whitespace away, using jQuerys $.trim():
var state = $.trim($('.check-state').text());
On a side note, I would recommend you to use console.log() instead of alert() for debugging. In most browsers, that would have allowed you to detect where the error was since you would have clearly seen the whitespace.

Struggling with some javascript, password / username error display

Note, I will validate everything with PHP on form submission, but I'd like to display it instantly to the user if possible.
For the username I am trying to detect if it only contains whitespace, if it's less than 8 chars/numbers and if it only contains normal valid letters and no symbols.
This does not seem to work:
$("#username").change(function() {
$("#username").removeClass("error");
var letterNumber = /^[0-9a-zA-Z]+$/;
var username = $("#username").val(); // get value of password
if (!(username.value.match(letterNumber)) {
// return error
}
if (username.length < 8) {
// return error
}
if (username.trim().length() > 0) {
// return error
}
});
And for the password, I want to allow all symbols, all numbers, all letters, minimum 8, and trim for whitespace. It does not seem to work though.
Change from this:
if (!(username.value.match(letterNumber)) {
// return error
}
to this:
if (!(username.match(letterNumber)) {
// return error
}
You've already retrieved the .value when you used .val() earlier so username is already the desired string.
Also, the .trim() test is not correct as .length is a property all by itself, not a method). But, you can just remove this because your regex test before has already eliminated empty strings and strings with only whitespace so this test (even when corrected to be proper javascript) is unnecessary.
if (username.trim().length() > 0) {
// return error
}
In the future, you should be looking in your browser error console or debug console because it would have told you something like undefined doesn't have a method .match() and given you that exact line number as the source of the error.

Categories