I am working on a generic isBlank function in JS like Java StringUtils.isBlank();
I would like your opinion on the implementation in case I missed something like == vs === or better implementation?
so the following are considerd blank:
var a; //undefined => true
var b = null; //null => true
var c = ''; //emptyString => true
var d = ' '; //emptyString => true
var e = ' \b \f \n \r \t \v \0 '; //emptyString with other white space => true
Implementation:
function isBlank(value){
return(value == undefined || value == null || value.trim() == '');
}
var a; //undefined => true
var b = null; //null => true
var c = ''; //emptyString => true
var d = ' '; //emptyString => true
var d1 = ' \b \f \n \r \t \v \0 ';
var e = 'X'; //char => false
var f = '#'; //char => false
var g = '1'; //digit => false
function isBlank(value){
return(value == undefined || value == null || value.trim() == '');
}
console.log('a => ' + isBlank(a));
console.log('b => ' + isBlank(b));
console.log('c => ' + isBlank(c));
console.log('d => ' + isBlank(d));
console.log('d1 => ' + isBlank(d1));
console.log('e => ' + isBlank(e));
console.log('f => ' + isBlank(f));
console.log('g => ' + isBlank(g));
You can shorten your function by using ! operator which will convert both undefined and null to true (since it negates falsy values):
var a; //undefined => true
var b = null; //null => true
var c = ''; //emptyString => true
var d = ' '; //emptyString => true
var e = 'X'; //char => false
var f = '#'; //char => false
var g = '1'; //digit => false
var h = 1; //digit => false
var d1 = ' \b \f \n \r \t \v \0 '; // whitespaces => true
var d2 = ' \b \f \n aa \r \t \v \0 '; // whitespaces with regular text => false
function isBlank(value){
return !value || !value.toString().trim() || /^[\s\b\0]+$/.test(value.toString());
}
console.log('a => ' + isBlank(a));
console.log('b => ' + isBlank(b));
console.log('c => ' + isBlank(c));
console.log('d => ' + isBlank(d));
console.log('e => ' + isBlank(e));
console.log('f => ' + isBlank(f));
console.log('g => ' + isBlank(g));
console.log('h => ' + isBlank(h));
console.log('h => ' + isBlank(d1));
console.log('h => ' + isBlank(d2));
EDIT: added isBlank2 to support numbers if needed
Related
I need to wrap r.title value with <b></b> tag.
I wanted to do so r.subtitle && (l = "<b>" + r.title + "</b>" + r.subtitle), but displays it in text.
This function
function (e, t, n) {
"use strict";
function r(e) {
return e && e.__esModule ? e : { default: e };
}
Object.defineProperty(t, "__esModule", { value: !0 });
var o = n(0),
a = r(o),
i = n(1),
l = r(i),
u = function (e) {
var t = e.className,
n = e.style,
r = e.track,
o = e.trackNo,
i = e.displayArtistNames,
l = r.title;
return i && r.subtitle && (l = r.title + " - " + r.subtitle), null != o && (l = o + ". " + l), a.default.createElement("span", { style: n }, l);
};
(u.propTypes = { track: l.default.object.isRequired, trackNo: l.default.number, style: l.default.object, className: l.default.string, displayArtistNames: l.default.bool }), (t.default = u);
},
You can use the .innerText property to set element's text or .innerHTML / .outerHTML to set the html-code inside or outside of html element tag:
var elementCode = "<b>" + title + "</b>";
document.body.innerHTML += elementCode;
You can also use create and append child functions (more recommended)
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');
}
After initialing an array, it contains empty elements. I want to set an element back to empty after setting an value. But it doesn't work however I set it to undefined/null.
var a = Array(20181231);
// it will not run.
a.forEach(e => {console.log(++i + ' - ' + e);});
var i = 0;
a[12] = 12;
a[2018] = 2018;
// it loop twice
a.forEach(e => {console.log(++i + ' - ' + e);});
a[12] = undefined;
// expecting one time, but it still loop twice.
a.forEach(e => {console.log(++i + ' - ' + e);});
You could take the delete operator and remove the element of the array.
var a = Array(20181231);
a.forEach(e => console.log(++i + ' - ' + e)); // no loop
var i = 0;
a[12] = 12;
a[2018] = 2018;
a.forEach(e => console.log(++i + ' - ' + e)); // two elements
delete a[12];
a.forEach(e => console.log(++i + ' - ' + e)); // one element
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));
});
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I trying to append the script to the page but I get the answer:
Invalid regular expression: missing /
Can someone please take a look and show me where is the problem in my RegEx code?
function init(){
var script = document.createElement("script");
script.type = "text/javascript";
script.text = 'jx = {'+
'b: function () {'+
'var b = !1;'+
'if ("undefined" != typeof ActiveXObject) { try {'+
'b = new ActiveXObject("Msxml2.XMLHTTP");'+
' } catch (c) {'+
' try {'+
' b = new ActiveXObject("Microsoft.XMLHTTP");'+
' } catch (a) {'+
' b = !1;'+
' }'+
' } } else { if (window.XMLHttpRequest) try {'+
' b = new XMLHttpRequest;'+
'} catch (h) {'+
' b = !1;'+
' }'+
'}'+
' return b;'+
' },'+
'load: function (b, c, a, h, g) {'+
' var e = this.d();'+
' if (e && b) {'+
' e.overrideMimeType && e.overrideMimeType("text/xml");'+
' h || (h = "GET");'+
' a || (a = "text");'+
' g || (g = {});'+
' a = a.toLowerCase();'+
' h = h.toUpperCase();'+
' b += b.indexOf("?") + 1 ? "&" : "?";'+
' var k = null;'+
' "POST" == h && (k = b.split("?"), b = k[0], k = k[1]);'+
' e.open(h, b, !0);'+
' e.onreadystatechange = g.c ? function () {'+
' g.c(e)'+
'} : function () {'+
' if (4 == e.readyState)'+
' if (200 == e.status) {'+
' var b = "";'+
' e.responseText && (b = e.responseText);'+
' "j" == a.charAt(0) ? (b = b.replace(/[\n\r]/g, ""), b = eval("(" + b + ")")) : "x" == a.charAt(0) && (b = e.responseXML);'+
' c && c(b)'+
' } else g.f && document.getElementsByTagName("body")[0].removeChild(g.f), g.e && (document.getElementById(g.e).style.display = "none"), error && error(e.status)'+
' };'+
' e.send(k);'+
' }'+
'},'+
' d: function () {'+
' return this.b()'+
' }'+
'};'+
'alert("loaded");';
document.body.appendChild(script);
}
Do you see a mistake!
quite apart from what you're doing, the problem is that you're not escaping the backslashes. the reges
/[\n\r]/g
By itself is perfectly fine, but you're not writing a literal RegExp instance, you're writing a string. In a string \n is an escape sequence for a new line. To get around this, escape the backslash:
var str = '/[\\n\\r]/g';
would do the trick