Remove "null" from string in javascript - javascript

I have this code:
var returnValue = item.fname + " " + item.mname + " " + item.lname
returnValue.replace(null," ");
return returnValue ;
Sometimes one of the fields is null so returnValue is:
"John null Doe"
or
"John something null"
I want to get rid of the "null" but my code does not seem to work.
Can someone help me out here?

Rather than replacing null afterwards, only append the individual names if they are not null.
var returnValue = "";
if (item.fname !== null) {
returnValue += item.fname + " ";
}
if (item.mname !== null) {
returnValue += item.mname + " ";
}
if (item.lname !== null) {
returnValue += item.lname;
}
return returnValue;
Alternatively, use Array.prototype.filter to remove nulls:
// store the names in an array
var names = [ item.fname, item.mname, item.lname ];
// filter the array to values where they are `!== null`
var notNullNames = names.filter(x => x !== null);
// join them with spaces
var returnValue = notNullNames.join(" ");

var returnValue = (item.fname || " ") + " " + (item.mname || " ") + " " + (item.lname || " ");
return returnValue;
Be careful with mixing var types (string and null for example). Better make sure the variable is set or has a fallback.

I'd recommend you another technique: place your string parts to array, filter it and join it:
[item.fname, item.mname, item.lname].filter(v => !!v).join(' ')

try this
> return (item.fname ? item.fname : '') + " " + (item.mname ? item.mname : '') + " " + (item.lname ? item.lname : '');

var returnValue = item.fname
if(item.mname)returnValue += " " + item.mname
if(item.lname)returnValue += " " + item.lname
return returnValue

Try ternary operator for null avoiding:
var returnValue = item.fname + " " + item.mname ? item.mname : "" + " " + item.lname

In my opinion, the most elegant solution is:
[item.fname, item.lname, item.lname].join(' ');
For example:
const item = {}
item.fname = 'foo'
item.lname = 'bar'
console.log([item.fname, item.mname, item.lname].join(' '))
Otherwise you can use the or operator to skip falsy objects:
const item = {}
item.fname = 'foo'
item.lname = 'bar'
const joined = (item.fname || '') + " " + (item.mname || '') + " " + (item.lname || '')
console.log(joined)

Related

Replacing null with 0 when summing values

I have a function that sums my values and everything works fine, but only when all inputs have a value entered. However, I would like default to have 0 assigned to it.so that the function works when at least one value is given . How to do it ?.
var DeductiblepercentageM = thisPointer.entity.getValue('number.DeductiblepercentageM[' + i + ']');
var InsuranceLimitM = thisPointer.entity.getValue('number.InsuranceLimitM[' + i + ']');
var insuranceRaitingM = thisPointer.entity.getValue('number.insuranceRaitingM[' + i + ']');
var InsurerNumberM = thisPointer.entity.getValue('number.InsurerNumberM[' + i + ']');
DeductiblepercentageM = DeductiblepercentageM.replace(",", ".");
DeductiblepercentageM = parseFloat(DeductiblepercentageM)
InsuranceLimitM = InsuranceLimitM.replace(",", ".");
InsuranceLimitM = parseFloat(InsuranceLimitM)
insuranceRaitingM = insuranceRaitingM.replace(",", ".");
insuranceRaitingM = parseFloat(insuranceRaitingM)
InsurerNumberM = InsurerNumberM.replace(",", ".");
InsurerNumberM = parseFloat(InsurerNumberM)
//log the outcome of decimal separator change
var positionSum = +(DeductiblepercentageM + InsuranceLimitM +insuranceRaitingM + InsurerNumberM);
jQ('[id="DeductibleM[' + i + ']"]').val(positionSum);
thisPointer.entity.setValue('DeductibleM[' + i + ']', positionSum);
thisPointer.entity.mergeLocal(true);
if (totalSum != "NaN") {
totalSum = +(totalSum + positionSum).toFixed();
}
}
else {
totalSum = "-";
}
According to #Terry
var InsuranceLimitM = thisPointer.entity.getValue('number.InsuranceLimitM[' + i + ']') || 0;
adding || 0 to the end of the code helps and makes the code count right away

How to get Google meet link thru google calendar api in javascript?

I want to create a line notify which can send the event detail from my google calendar everyday.
I can get the title, description, location...etc, but I don't see the conference data in calendar API.
I use Google Apps Script to run the code.
Here is my code.
const Now = new Date();
const Start = new Date(new Date().setHours(0, 0, 0, 0));
const End = new Date(new Date().setHours(23, 59, 59, 999));
const calendarData = calendar.getEvents(Start, End);
function Notify() {
var NotifyContents = '';
var i = 1;
calendarData.forEach(item =>{
if (Now <= item.getStartTime()) {
NotifyContents += (item.getTitle() != "") ? ("\n" + i+". "+ item.getTitle() + "\n") : ("\n\nNo Title\n");
NotifyContents += (item.getDescription() != "") ? item.getDescription() + "\n" : "";
NotifyContents += (item.getStartTime() != "" && item.getEndTime() != "") ? "Time:" + item.getStartTime().toLocaleTimeString() + "-" + item.getEndTime().toLocaleTimeString() + "\n": "";
NotifyContents += (item.getconferencedata() != "") ? ("\n" + i+". "+ item.getconferencedata()) : ("No Conference\n");
i++;
}
}
)
if (typeof NotifyContents === 'string' && NotifyContents.length === 0) {
return;
}
NotifyTokens.forEach(function(value){
UrlFetchApp.fetch("https://notify-api.line.me/api/notify", {
"method" : "post",
"payload" : {"message" : NotifyContents},
"headers" : {"Authorization" : "Bearer " + value}
});
});
}
Reference - Calendar API Link
In order to retrieve the meet link from the event, it seems that in the current stage, Calendar API is required to be used. When this is reflected in your script, how about the following modification?
Modified script:
Before you use this script, please enable Calendar API at Advanced Google services.
From:
var NotifyContents = '';
var i = 1;
calendarData.forEach(item => {
if (Now <= item.getStartTime()) {
NotifyContents += (item.getTitle() != "") ? ("\n" + i + ". " + item.getTitle() + "\n") : ("\n\nNo Title\n");
NotifyContents += (item.getDescription() != "") ? item.getDescription() + "\n" : "";
NotifyContents += (item.getStartTime() != "" && item.getEndTime() != "") ? "Time:" + item.getStartTime().toLocaleTimeString() + "-" + item.getEndTime().toLocaleTimeString() + "\n" : "";
NotifyContents += (item.getconferencedata() != "") ? ("\n" + i + ". " + item.getconferencedata()) : ("No Conference\n");
i++;
}
}
)
To:
const eventList = Calendar.Events.list(calendar.getId(), { timeMin: Start.toISOString(), timeMax: End.toISOString(), maxResults: 2500 }).items.reduce((o, e) => (o[e.id] = e.conferenceData.entryPoints.map(({ uri }) => uri).join(","), o), {});
var NotifyContents = '';
var i = 1;
calendarData.forEach(item => {
if (Now <= item.getStartTime()) {
NotifyContents += (item.getTitle() != "") ? ("\n" + i + ". " + item.getTitle() + "\n") : ("\n\nNo Title\n");
NotifyContents += (item.getDescription() != "") ? item.getDescription() + "\n" : "";
NotifyContents += (item.getStartTime() != "" && item.getEndTime() != "") ? "Time:" + item.getStartTime().toLocaleTimeString() + "-" + item.getEndTime().toLocaleTimeString() + "\n" : "";
var eventId = item.getId().split("#")[0];
NotifyContents += eventList[eventId] != "" ? ("\n" + i + ". " + eventList[eventId]) : ("No Conference\n");
i++;
}
});
In this modification, it supposes that calendar has already been declaread. Please be careful about this.
Reference:
Events: list

Done / How to make a space printer in javascript

var arg = 5
var string = ' '
for (let i = 0; i < arg; i++) {
console.log('"' + string + '"')
}
I expected the output is:
" " \\ There are 5 spaces between the ""
But the output is:
" "
" "
" "
" "
" "
I am a newbie in javascript. Hope you will help me
you can use method string.padEnd that fill string with blank space until parameter pass to the method
var arg = 5;
var string = ' ';
string = string.padEnd(arg)
console.log('"' + string + '"');
reference : https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd
I don't think there is a way to console.log on the same line. You can do something like this
var arg = 5
var string = ' '
var final_string = ''
for (let i = 0; i < arg; i++)
final_string = final_string + string
}
console.log('"' + final_string + '"')
I think you can use or \xa0 for printing spaces
var arg = 5
var string = '\xa0\xa0\xa0\xa0\xa0';
for (let i = 0; i < arg; i++) {
console.log('"' + string + '"')
}
There are many ways to do this. One would be to do it via a loop. That way you can stay flexible. For loop has already been mentioned. here with a foreach loop.
let string = '';
[...Array(5).keys()].forEach(e => string += ' ');
console.log('"' + string + '"');

Matching a String with Array of String in Java Script

str1 = booking_kode.substring(0, 3);
B = ["800", "807", "826", "847", "866"];
C = ["827", "846"];
E = ["867", "879"];
F = ["880", "899"];
if (str1 = array B){
print ('Prefix , first 3 digit = ' + str1 + '\n')
comm_code = 'B000'
print ('Comm_Code = ' + comm_code + '\n')
}
else if (str1 = array C) {
print ('Prefix , first 3 digit = ' + str1 + '\n')
comm_code = 'C000'
print ('Comm_Code = ' + comm_code + '\n')
}
else if (str1 = array E) {
print ('Prefix , first 3 digit = ' + str1 + '\n')
comm_code = 'E000'
print ('Comm_Code = ' + comm_code + '\n')
}
else if (str1 = array F) {
print ('Prefix , first 3 digit = ' + str1 + '\n')
comm_code = 'F000'
print ('Comm_Code = ' + comm_code + '\n')
}
else {
print ('Prefix , Nilai 3 digit pertama = ' + str1 + '\n')
comm_code = 'D000'
print ('Comm_Code = ' + comm_code + '\n')
}
Hello,
I want to know how to match the string Str1 with the value of the Array B,C,E,F.
I mean :
If Str1 = 800|| 807 || 826 || 847 || 866, Then Comm_code = B000
If Str1 = 827 || 846 then Comm_code = C000
If Str1 = 867 || 879 then Comm_code = E000
If Str1 = 880 || 899 then Comm_code = F000
Else Default --> Comm_code = D000
Please kindly advice.
p.s. : Fyi, I'm using EcmaScript 2015 / ES5.
Just use a simple String.prototype.indexOf:
str1 = booking_kode.substring(0, 3);
B = ["800", "807", "826", "847", "866"];
C = ["827", "846"];
E = ["867", "879"];
F = ["880", "899"];
if (B.indexOf(str1) > -1)
{
print ('Prefix , first 3 digit = ' + str1 + '\n');
comm_code = 'B000';
print ('Comm_Code = ' + comm_code + '\n');
}
else if (C.indexOf(str1) > -1)
{
print ('Prefix , first 3 digit = ' + str1 + '\n');
comm_code = 'C000';
print ('Comm_Code = ' + comm_code + '\n');
}
else if (E.indexOf(str1) > -1)
{
print ('Prefix , first 3 digit = ' + str1 + '\n');
comm_code = 'E000';
print ('Comm_Code = ' + comm_code + '\n');
}
else if (F.indexOf(str1) > -1)
{
print ('Prefix , first 3 digit = ' + str1 + '\n');
comm_code = 'F000';
print ('Comm_Code = ' + comm_code + '\n');
}
else
{
print ('Prefix , Nilai 3 digit pertama = ' + str1 + '\n');
comm_code = 'D000';
print ('Comm_Code = ' + comm_code + '\n');
}
You can achieve this with simple if else conditions using Array.indexOf() Methods. However make sure the str1 and the values in the array are of same variable type(string or a number).
if (B.indexOf(str1) > -1 ) { //if value exists in B
//do soemthing;
}
else if(C.indexof(str1) >-1 ) { //if value exists in C
//do soemthing
}
One possible solution to solve this is use Array.some() (I think it is included on ES5 based on this link). First you can create a method that will check if an element is on an array:
function arrayIncludes(arr, ele)
{
return arr.some(function(x) {return (x === ele);});
}
console.log(arrayIncludes([1,2], 2));
console.log(arrayIncludes([1,2], 5));
.as-console {background-color:black !important; color:lime;}
Then, your code can be reworked to this:
str1 = booking_kode.substring(0, 3);
B = ["800", "807", "826", "847", "866"];
C = ["827", "846"];
E = ["867", "879"];
F = ["880", "899"];
function arrayIncludes(arr, ele)
{
return arr.some(function(x) {return (x === ele);});
}
if (arrayIncludes(B, str1))
{
print ('Prefix , first 3 digit = ' + str1 + '\n');
comm_code = 'B000';
print ('Comm_Code = ' + comm_code + '\n');
}
else if (arrayIncludes(C, str1))
{
print ('Prefix , first 3 digit = ' + str1 + '\n');
comm_code = 'C000';
print ('Comm_Code = ' + comm_code + '\n');
}
else if (arrayIncludes(E, str1))
{
print ('Prefix , first 3 digit = ' + str1 + '\n');
comm_code = 'E000';
print ('Comm_Code = ' + comm_code + '\n');
}
else if (arrayIncludes(F, str1))
{
print ('Prefix , first 3 digit = ' + str1 + '\n');
comm_code = 'F000';
print ('Comm_Code = ' + comm_code + '\n');
}
else
{
print ('Prefix , Nilai 3 digit pertama = ' + str1 + '\n');
comm_code = 'D000';
print ('Comm_Code = ' + comm_code + '\n');
}

Object.keys(arr).reduce() returns undefined

I am creating an object from an array like so
var val = $(this).val();
var type = " " + $("#backing").val() + " ";
var arr = $.extend({}, comb_arr[type]);
The result
var arr = {"1-4 ": "$10.10 ", "5-9 ": "$8.34 ", "10-24 ": "$7.71 ", "25-49 ": "$7.21 "}
When I run the below code through the output is undefined
var price = Object.keys(arr).reduce((a, c) => {
var s = c.trim();
if(/\d+\-\d+/.test(s)){
var range = s.split("-");
if(val >= parseInt(range[0]) && val <= parseInt(range[1])){
a = comb_arr[c];
}
}else{
s = s.replace(/\D/g, "");
if(val >= s){
a = comb_arr[c];
}
}
return a;
},0);
All ideas are welcome!

Categories