Matching a String with Array of String in Java Script - javascript

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');
}

Related

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 + '"');

Javascript for Phone Number Formatting in Dynamics 365

Javascript we had for Unified interface of Dynamics 365 to format phone numbers was working perfectly until the latest update, now it only works in custom interface and has stopped working in UI, anybody has any idea how this can be fixed?
var XXX = window.XXX || {};
(function() {
// Code to run in the form OnLoad event
this.formOnLoad = function(executionContext) {
var formContext = executionContext.getFormContext();
// display the form level notification as an INFO
formContext.ui.setFormNotification(message, "INFO", myUniqueId);
// Wait for 5 seconds before clearing the notification
window.setTimeout(function() {
formContext.ui.clearFormNotification(myUniqueId);
}, 5000);
}
// Code to run in the attribute OnChange event
this.mobilePhoneFormatting = function(executionContext) {
var formContext = executionContext.getFormContext();
var mobilePhone = formContext.getAttribute("mobilephone").getValue();
var formatPhone = "";
try {
if (mobilePhone != null) {
var phoneNumbers = mobilePhone.replace(/\D/g, '');
if (phoneNumbers.length == 10) { //10 digit case. Output adds +1 and proper format
formatPhone = ("+1 (" + phoneNumbers.substring(0, 3) + ") " + phoneNumbers.substring(3, 6) + "-" + phoneNumbers.substring(6, 10));
} else if (phoneNumbers.length == 11) { //11 digit case. Output proper format
formatPhone = ("+" + phoneNumbers.substring(0, 1) + " (" + phoneNumbers.substring(1, 4) + ") " + phoneNumbers.substring(4, 7) + "-" + phoneNumbers.substring(7, 11));
} else if (phoneNumbers.length == 14) { //14 digit case. Without Country code and with extension
formatPhone = ("+1 (" + phoneNumbers.substring(0, 3) + ") " + phoneNumbers.substring(3, 6) + "-" + phoneNumbers.substring(6, 10) + " x" + phoneNumbers.substring(10, 14));
} else if (phoneNumbers.length == 15) { //15 digit case. With Country code and extension
formatPhone = ("+" + phoneNumbers.substring(0, 1) + " (" + phoneNumbers.substring(1, 4) + ") " + phoneNumbers.substring(4, 7) + "-" + phoneNumbers.substring(7, 11) + " x" + phoneNumbers.substring(11, 15));
} else if (phoneNumbers.length == 4) { //4 digit case. Extension Only
formatPhone = ("x" + phoneNumbers.substring(0, 4));
} else {
formatPhone = mobilePhone;
}
formContext.getAttribute("mobilephone").setValue(formatPhone);
formContext.data.entity.save();
}
} catch (err) {
txt = "There was an error formatting the Phone Number.\n\n";
txt += "Error description: " + err.message + "\n\n";
txt += "Click OK to continue.\n\n";
alert(txt);
}
}

Remove "null" from string in 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)

How can I add regex for this one?

I want to add comma between Haircut and Wash. basically like this: Haircut, Wash And Blow Dry
if(string === 'HaircutWashAndBlowDry'){
string.charAt(0).toUpperCase() + string.slice(1);
str = str.replace(/([A-Z])/g, ' $1').trim();
}
You don't need to lowercase first letter. Use \B along with a simple counter:
var str = 'HaircutWashAndBlowDry';
var i = 1;
console.log(str.replace(/\B([A-Z])/g, function(match, $1) {
return ( i++ == 1 ? ', ' : ' ' ) + $1;
}))
Funny goal :) Let's play a bit with two previous answers (testCase 2 & testCase 3) that relies on words positions and a wider approach that relies on splitting on the And string to behave differently :
// Haircut, Wash And Blow Dry
let strings = [
'HaircutWashAndBlowDry',
'HaircutWashCleanAndBlowDrySet'
];
function testCase1(str) {
let pieces = str.split('And');
pieces[0] = pieces[0].replace(/([a-z])([A-Z])/g, '$1, $2');
pieces[1] = pieces[1].replace(/([a-z])([A-Z])/g, '$1 $2');
return pieces[0] + ' And ' + pieces[1];
}
function testCase2(string) {
return string.replace(/^([A-Z][^A-Z]*)([A-Z])|([A-Z])/g, function($0,$1,$2,$3) {return $2 ? $1 + ", " + $2 : " " + $3 ;});
}
function testCase3(str) {
let i = 1;
return str.replace(/\B([A-Z])/g, function(match, $1) {
return ( i++ == 1 ? ', ' : ' ' ) + $1;
});
}
strings.forEach(str => {
console.log(str);
console.log('testCase1 : ' + testCase1(str));
console.log('testCase2 : ' + testCase2(str));
console.log('testCase3 : ' + testCase3(str));
});

Split string with JavaScript

how to parse this string with java script
19 51 2.108997
20 47 2.1089
like this
<span>19 51</span> <span>2.108997</span>
<span>20 47</span> <span>2.1089</span>
Assuming you're using jQuery..
var input = '19 51 2.108997\n20 47 2.1089';
var lines = input.split('\n');
var output = '';
$.each(lines, function(key, line) {
var parts = line.split(' ');
output += '<span>' + parts[0] + ' ' + parts[1] + '</span><span>' + parts[2] + '</span>\n';
});
$(output).appendTo('body');
Like this:
var myString = "19 51 2.108997";
var stringParts = myString.split(" ");
var html = "<span>" + stringParts[0] + " " + stringParts[1] + "</span> <span>" + stringParts[2] + "</span";
var wrapper = $(document.body);
strings = [
"19 51 2.108997",
"20 47 2.1089"
];
$.each(strings, function(key, value) {
var tmp = value.split(" ");
$.each([
tmp[0] + " " + tmp[1],
tmp[2]
], function(key, value) {
$("<span>" + value + "</span>").appendTo(wrapper);
});
});

Categories