Javascript, String: Getting a Javascript var as a string - javascript

Because using .toString() for null vars doesn't work, and I can't be checking each and every one of these in my particular application.
I know this is a stupidly simple problem with an answer that literally must be staring me in the face right now.

The non-concatenation route is to use the String() constructor:
var str = new String(myVar); // returns string object
var str = String(myVar); // returns string value
Of course, var str = "" + myVar; is shorter and easier. Be aware that all the methods here will transform a variable with a value of null into "null". If you want to get around that, you can use || to set a default when a variable's value is "falsey" like null:
var str = myVar || "";
Just so long as you know that 0 and false would also result in "" here.
https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/String

How about
var str = '' + someVar;

What about
var str = (variable || "");
//or
(variable || "").toString();
Of course you'll get this for false, undefined and so on, too, but it will be an empty string and not "null"

String(null) returns "null", which may cause problems if a form field's value is itself null. How about a simple wrapper function instead?
function toString(v) {
if(v == null || v == undefined) {
return "";
}
return String(v);
}
Only null, undefined, and empty strings should return the empty string. All other falsy values including the integer 0 will return something else. Some tests,
> toString(null)
""
> toString(undefined)
""
> toString(false)
"false"
> toString(0)
"0"
> toString(NaN)
"NaN"
> toString("")
""

How about ... ?
var theVarAsString = "" + oldVar;

Related

Assign 0 if the value is null or empty in Jquery

I want to use a ternary operator for the below jQuery statement like if employee_salary is empty or null, I want to assign as 0 (zero). Otherwise, just assign the actual value.
jQuery('#employee_form #employee_salary').val(parseInt(selected_table_data['employee_salary']))
var employee_salary = selected_table_data['employee_salary'];
var salary_form_value = employeeSalary ? parseInt(employee_salary) : '0';
jQuery('#employee_form #employee_salary').val(salary_form_value);
// If you want to inline it, you could do the following:
jQuery('#employee_form #employee_salary').val(
selected_table_data['employee_salary']
? parseInt(selected_table_data['employee_salary']
: 0
);
Here is an example
const s1 = null;
console.log(s1 ? s1 : 'There was a null value');
const s2 = ''
console.log(s2 ? s2 : 'There was an empty string');
const s3 = 'value';
console.log(s3 ? s3 : 'There was no value');
You can use ternary operator simply.
selected_table_data['employee_salary']
? parseInt(selected_table_data['employee_salary'])
: 0
console.log('' || 0);
console.log(null || 0);
console.log(undefined || 0);
I suspect that parseInt was your attempt to make this work yourself (fair enough). I'm going to suggest you remove it and try simply
jQuery('#employee_form #employee_salary').val(selected_table_data['employee_salary'] || 0);
A simple solution for you.
jQuery('#employee_form #employee_salary').val(selected_table_data['employee_salary'] * 1)
Using || operator or just a simple ternary operator would work if its null, undefined or ''. But it won't work for a blank space like this one ' ' (since Boolean (' ') evaluates as true) which it's not good if you want to replace any empty string or blank spaces for zero. So I would suggest you to do something like this,
jQuery('#employee_form #employee_salary').val(parseInt(selected_table_data['employee_salary']) ? parseInt(selected_table_data['employee_salary']) : 0);
This will allow you not only check if null, undefined, empty string and white spaces but also will prevent NaN to be a value on your form (instead zero will take place).

How to check string length in JavaScript?

How can I check the length of in String in JavaScript? Here is a small code example:
if(value != null && value != "" && value.length !== 10 && !value.match(/^\d*$/)){
// do something
}
The expression 'value.length !== 10' doesn´t work. A String must contain at least 10 characters. How can I solve this problem?
Instead of match, test can be used with proper regex \d{10,}.
if (value && /^\d{10,}$/.test(value.trim()))
To Get the string length of a value for example:
var value="This is a string";
var string_length=value.length;
/*The string length will result to 16*/
Hope this helps
var regex = new RegExp(/^\d*$/),
value = $.trim("1234567890");
if (value.length >= 10 && regex.exec(value)) {
// correct
} else {
// incorrect
}

converting string into Boolean value using JavaScript always give false

I am using the code below in JavaScript to change a string on the site to a Boolean value using JavaScript. when I alert test its says its true, but when I alter name bool is see flase any ideas why this would be the case.
var test = document.getElementById("name").value;
var nameBool= (String == test);
Compare the string to the value that you expect it to have when it should represent a true value:
var nameBool = test === "true";
I would guess that test is the boolean value of a checkbox? Then you would get a textual representation of it either by
var nameBool = String(test); // type conversion
or simpler
var nameBool = "" + test; // concatenation with empty string - implicit conversion
which then becomes "false" or "true", just as in your alert() (which did a stringification as well)
For the opposite, you'd use
var test = "true" // or "false"
var nameBool = test === "true" || (test === "false" ? false : throw new SyntaxError("non-boolean string value"));

Javascript syntax issue

Here is my jsFiddle
Its on the Phone method, no the name one
Now is this line right? I only want it to be true if the first 3 letters are 087
var RightStarting3 = value.substring(0,2) == (087);
if (BlankPass || LessThan10 || RightStarting3 || GreaterThan10 || (HasSpaces > 0))
{
document.getElementById('Phone').style.background = "red";
return false;
}
else {
document.getElementById('Phone').style.background = "white";
document.getElementById("PhoneTick").style.visibility="visible";
return true;
}
var RightStarting3 = value.substring(0,3) === ('087');
value.substring(x) returns a string and 087 and 87 mean the same to javascript interpreter. You should change one of the datatypes so that they match...
Either the substring to an integer:
var RightStarting3 = parseInt(value.substring(0,2)) == 87;
Or the value you're comparing against to a string:
var RightStarting3 = value.substring(0,3) == "087";
Secondly -- you are invoking ValidateName() immediately (in your assignment to NamePass). Is this really necessary? There will be empty values on page load.
I think with the javascript substring(x,y) method, the y value is the value at which to stop the selection. So in your example the first 3 characters will not be selected and instead the first 2 characters will be selected.
var a = "123";
// this returns "12"
alert(a.substring(0,2));
You probably want to use var RightStarting3 = value.substring(0,3) == ('087'); instead.
KingKongFrom's answer is correct, I would add that you should make sure that value (whatever that is) isn't null first, cause if you try to call substring on null it will thrown an exception and die.

How to check if a variable is null or empty string or all whitespace in JavaScript?

I need to check to see if a variable is null or has all empty spaces or is just blank ("").
I have the following, but it is not working:
var addr;
addr = " ";
if (!addr) {
// pull error
}
If I do the following, it works:
if (addr) {
}​
What I need is something like the C# method String.IsNullOrWhiteSpace(value).
A non-jQuery solution that more closely mimics IsNullOrWhiteSpace, but to detect null, empty or all-spaces only:
function isEmptyOrSpaces(str){
return str === null || str.match(/^ *$/) !== null;
}
...then:
var addr = ' ';
if(isEmptyOrSpaces(addr)){
// error
}
* EDIT *
Please note that op specifically states:
I need to check to see if a var is null or has any empty spaces or for that matter just blank.
So while yes, "white space" encompasses more than null, spaces or blank my answer is intended to answer op's specific question. This is important because op may NOT want to catch things like tabs, for example.
if (addr == null || addr.trim() === ''){
//...
}
A null comparison will also catch undefined. If you want false to pass too, use !addr. For backwards browser compatibility swap addr.trim() for $.trim(addr).
You can use if(addr && (addr = $.trim(addr)))
This has the advantage of actually removing any outer whitespace from addr instead of just ignoring it when performing the check.
Reference: http://api.jquery.com/jQuery.trim/
Old question, but I think it deservers a simpler answer.
You can simply do:
var addr = " ";
if (addr && addr.trim()) {
console.log("I'm not null, nor undefined, nor empty string, nor string composed of whitespace only.");
}
Simplified version of the above: (from here: https://stackoverflow.com/a/32800728/47226)
function isNullOrWhitespace( input ) {
return !input || !input.trim();
}
You can create your own method Equivalent to
String.IsNullOrWhiteSpace(value)
function IsNullOrWhiteSpace( value) {
if (value== null) return true;
return value.replace(/\s/g, '').length == 0;
}
isEmptyOrSpaces(str){
return !str || str.trim() === '';
}
When checking for white space the c# method uses the Unicode standard. White space includes spaces, tabs, carriage returns and many other non-printing character codes. So you are better of using:
function isNullOrWhiteSpace(str){
return str == null || str.replace(/\s/g, '').length < 1;
}
isEmptyOrSpaces(str){
return str === null || str.trim().length>0;
}
Try this out
/**
* Checks the string if undefined, null, not typeof string, empty or space(s)
* #param {any} str string to be evaluated
* #returns {boolean} the evaluated result
*/
function isStringNullOrWhiteSpace(str) {
return str === undefined || str === null
|| typeof str !== 'string'
|| str.match(/^ *$/) !== null;
}
You can use it like this
isStringNullOrWhiteSpace('Your String');
function isEmptyOrSpaces(str){
return str === null || str.match(/^[\s\n\r]*$/) !== null;
}
I use simply this and this works for me most of the time.
it first trim the white spaces and then checks the length.
if(value.trim().length === 0)
{
//code for empty value
}
Maybe it's easier this way
if (!addr?.trim()){
//error
}
Based on Madbreaks' answer, and I wanted to account for undefined as well:
function isNullOrWhitespace(str) {
return str == null || str.match(/^\s*$/) !== null;
}
Jest tests:
it('works for undefined', () => {
expect(isNullOrWhitespace(undefined)).toEqual(true);
});
it('works for null', () => {
expect(isNullOrWhitespace(null)).toEqual(true);
});
it('works for empty', () => {
expect(isNullOrWhitespace('')).toEqual(true);
});
it('works for whitespace', () => {
expect(isNullOrWhitespace(' ')).toEqual(true);
// Tab
expect(isNullOrWhitespace(' ')).toEqual(true);
});
You can try this:
do {
var op = prompt("please input operatot \n you most select one of * - / * ")
} while (typeof op == "object" || op == "");
// execute block of code when click on cancle or ok whthout input

Categories