Prevent value of 0 evaluating to false when using logical OR - javascript

I am wondering if there was a way around this issue. I am currently storing a value in a variable like so:
Session['Score'] = 0;
Later I have an assignment like so:
Score = Session['Score'] || 'not set';
The problem is, when Session['Score'] is set to 0 as above, JavaScript will interpret it as:
Score = false || 'not set';
which means Score will evaluate to 'not set' instead of 0!
How can I get around this issue?

Nowadays you can use the nullish coalescing operator (??) instead of the logical OR. It is similar to the logical OR, except that it only returns the right-hand side when the left-hand side is nullish (null or undefined) instead of falsy.
score = Session['Score'] ?? 'not set';
Old answer:
The cleanest way is probably to set the value and then check if it is falsy but not equal to 0
let score = Session['Score'];
if (!score && score !== 0) {
score = 'not set';
}
As mentioned by Patrick Roberts, you could also choose to use the conditional (ternary) operator in combination with the in operator:
Score = 'Score' in Session ? Session.Score : 'not set'

You can do this with destructuring assignment:
let { Score = 'not set' } = Session;
If it's not set:
const Session = { };
let { Score = 'not set' } = Session;
console.log( Score );
If it is set to any value other than undefined, including falsy ones:
const Session = { Score: 0 };
let { Score = 'not set' } = Session;
console.log( Score );

You could be more explicit about your intent by creating a few functions:
function getScore(s)
{
var result = s["Score"];
if (result == null) {
result = 0;
}
return result;
}
function addScore(s, v)
{
var result = s["Score"];
if (result == null) {
result = 0;
}
result += v;
s["Score"] = result;
return result;
}
var Session = {};
document.write("Score ");
document.write(getScore(Session));
document.write("<p/>");
addScore(Session, 10);
document.write("Score ");
document.write(getScore(Session));
Expected output:
Score 0
Score 10

Use a string instead:
Session['Score'] = "0";
Score = Session['Score'] || 'not set';

Related

Boolean conditionals with placeholder [duplicate]

Is there a string.Empty in JavaScript, or is it just a case of checking for ""?
Empty string, undefined, null, ...
To check for a truthy value:
if (strValue) {
// strValue was non-empty string, true, 42, Infinity, [], ...
}
To check for a falsy value:
if (!strValue) {
// strValue was empty string, false, 0, null, undefined, ...
}
Empty string (only!)
To check for exactly an empty string, compare for strict equality against "" using the === operator:
if (strValue === "") {
// strValue was empty string
}
To check for not an empty string strictly, use the !== operator:
if (strValue !== "") {
// strValue was not an empty string
}
For checking if a variable is falsey or if it has length attribute equal to zero (which for a string, means it is empty), I use:
function isEmpty(str) {
return (!str || str.length === 0 );
}
(Note that strings aren't the only variables with a length attribute, arrays have them as well, for example.)
Alternativaly, you can use the (not so) newly optional chaining and arrow functions to simplify:
const isEmpty = (str) => (!str?.length);
It will check the length, returning undefined in case of a nullish value, without throwing an error. In the case of an empty value, zero is falsy and the result is still valid.
For checking if a variable is falsey or if the string only contains whitespace or is empty, I use:
function isBlank(str) {
return (!str || /^\s*$/.test(str));
}
If you want, you can monkey-patch the String prototype like this:
String.prototype.isEmpty = function() {
// This doesn't work the same way as the isEmpty function used
// in the first example, it will return true for strings containing only whitespace
return (this.length === 0 || !this.trim());
};
console.log("example".isEmpty());
Note that monkey-patching built-in types are controversial, as it can break code that depends on the existing structure of built-in types, for whatever reason.
All the previous answers are good, but this will be even better. Use dual NOT operators (!!):
if (!!str) {
// Some code here
}
Or use type casting:
if (Boolean(str)) {
// Code here
}
Both do the same function. Typecast the variable to Boolean, where str is a variable.
It returns false for null, undefined, 0, 000, "", false.
It returns true for all string values other than the empty string (including strings like "0" and " ")
The closest thing you can get to str.Empty (with the precondition that str is a String) is:
if (!str.length) { ...
If you need to make sure that the string is not just a bunch of empty spaces (I'm assuming this is for form validation) you need to do a replace on the spaces.
if(str.replace(/\s/g,"") == ""){
}
I use:
function empty(e) {
switch (e) {
case "":
case 0:
case "0":
case null:
case false:
case undefined:
return true;
default:
return false;
}
}
empty(null) // true
empty(0) // true
empty(7) // false
empty("") // true
empty((function() {
return ""
})) // false
Performance
I perform tests on macOS v10.13.6 (High Sierra) for 18 chosen solutions. Solutions works slightly different (for corner-case input data) which was presented in the snippet below.
Conclusions
the simple solutions based on !str,==,=== and length are fast for all browsers (A,B,C,G,I,J)
the solutions based on the regular expression (test,replace) and charAt are slowest for all browsers (H,L,M,P)
the solutions marked as fastest was fastest only for one test run - but in many runs it changes inside 'fast' solutions group
Details
In the below snippet I compare results of chosen 18 methods by use different input parameters
"" "a" " "- empty string, string with letter and string with space
[] {} f- array, object and function
0 1 NaN Infinity - numbers
true false - Boolean
null undefined
Not all tested methods support all input cases.
function A(str) {
let r=1;
if (!str)
r=0;
return r;
}
function B(str) {
let r=1;
if (str == "")
r=0;
return r;
}
function C(str) {
let r=1;
if (str === "")
r=0;
return r;
}
function D(str) {
let r=1;
if(!str || 0 === str.length)
r=0;
return r;
}
function E(str) {
let r=1;
if(!str || /^\s*$/.test(str))
r=0;
return r;
}
function F(str) {
let r=1;
if(!Boolean(str))
r=0;
return r;
}
function G(str) {
let r=1;
if(! ((typeof str != 'undefined') && str) )
r=0;
return r;
}
function H(str) {
let r=1;
if(!/\S/.test(str))
r=0;
return r;
}
function I(str) {
let r=1;
if (!str.length)
r=0;
return r;
}
function J(str) {
let r=1;
if(str.length <= 0)
r=0;
return r;
}
function K(str) {
let r=1;
if(str.length === 0 || !str.trim())
r=0;
return r;
}
function L(str) {
let r=1;
if ( str.replace(/\s/g,"") == "")
r=0;
return r;
}
function M(str) {
let r=1;
if((/^\s*$/).test(str))
r=0;
return r;
}
function N(str) {
let r=1;
if(!str || !str.trim().length)
r=0;
return r;
}
function O(str) {
let r=1;
if(!str || !str.trim())
r=0;
return r;
}
function P(str) {
let r=1;
if(!str.charAt(0))
r=0;
return r;
}
function Q(str) {
let r=1;
if(!str || (str.trim()==''))
r=0;
return r;
}
function R(str) {
let r=1;
if (typeof str == 'undefined' ||
!str ||
str.length === 0 ||
str === "" ||
!/[^\s]/.test(str) ||
/^\s*$/.test(str) ||
str.replace(/\s/g,"") === "")
r=0;
return r;
}
// --- TEST ---
console.log( ' "" "a" " " [] {} 0 1 NaN Infinity f true false null undefined ');
let log1 = (s,f)=> console.log(`${s}: ${f("")} ${f("a")} ${f(" ")} ${f([])} ${f({})} ${f(0)} ${f(1)} ${f(NaN)} ${f(Infinity)} ${f(f)} ${f(true)} ${f(false)} ${f(null)} ${f(undefined)}`);
let log2 = (s,f)=> console.log(`${s}: ${f("")} ${f("a")} ${f(" ")} ${f([])} ${f({})} ${f(0)} ${f(1)} ${f(NaN)} ${f(Infinity)} ${f(f)} ${f(true)} ${f(false)}`);
let log3 = (s,f)=> console.log(`${s}: ${f("")} ${f("a")} ${f(" ")}`);
log1('A', A);
log1('B', B);
log1('C', C);
log1('D', D);
log1('E', E);
log1('F', F);
log1('G', G);
log1('H', H);
log2('I', I);
log2('J', J);
log3('K', K);
log3('L', L);
log3('M', M);
log3('N', N);
log3('O', O);
log3('P', P);
log3('Q', Q);
log3('R', R);
And then for all methods I perform speed test case str = "" for browsers Chrome v78.0.0, Safari v13.0.4, and Firefox v71.0.0 - you can run tests on your machine here
You can use lodash:
_.isEmpty(value).
It covers a lot of cases like {}, '', null, undefined, etc.
But it always returns true for Number type of JavaScript primitive data types like _.isEmpty(10) or _.isEmpty(Number.MAX_VALUE) both returns true.
Very generic "All-In-One" Function (not recommended though):
function is_empty(x)
{
return ( //don't put newline after return
(typeof x == 'undefined')
||
(x == null)
||
(x == false) //same as: !x
||
(x.length == 0)
||
(x == 0) // note this line, you might not need this.
||
(x == "")
||
(x.replace(/\s/g,"") == "")
||
(!/[^\s]/.test(x))
||
(/^\s*$/.test(x))
);
}
However, I don't recommend to use that, because your target variable should be of specific type (i.e. string, or numeric, or object?), so apply the checks that are relative to that variable.
var s; // undefined
var s = ""; // ""
s.length // 0
There's nothing representing an empty string in JavaScript. Do a check against either length (if you know that the var will always be a string) or against ""
Try:
if (str && str.trim().length) {
//...
}
I would not worry too much about the most efficient method. Use what is most clear to your intention. For me that's usually strVar == "".
As per the comment from Constantin, if strVar could some how end up containing an integer 0 value, then that would indeed be one of those intention-clarifying situations.
A lot of answers, and a lot of different possibilities!
Without a doubt for quick and simple implementation the winner is: if (!str.length) {...}
However, as many other examples are available. The best functional method to go about this, I would suggest:
function empty(str)
{
if (typeof str == 'undefined' || !str || str.length === 0 || str === "" || !/[^\s]/.test(str) || /^\s*$/.test(str) || str.replace(/\s/g,"") === "")
return true;
else
return false;
}
A bit excessive, I know.
check that var a; exist
trim out the false spaces in the value, then test for emptiness
if ((a)&&(a.trim()!=''))
{
// if variable a is not empty do this
}
You could also go with regular expressions:
if((/^\s*$/).test(str)) { }
Checks for strings that are either empty or filled with whitespace.
I usually use something like this,
if (!str.length) {
// Do something
}
Also, in case you consider a whitespace filled string as "empty".
You can test it with this regular expression:
!/\S/.test(string); // Returns true if blank.
If one needs to detect not only empty but also blank strings, I'll add to Goral's answer:
function isEmpty(s){
return !s.length;
}
function isBlank(s){
return isEmpty(s.trim());
}
if ((str?.trim()?.length || 0) > 0) {
// str must not be any of:
// undefined
// null
// ""
// " " or just whitespace
}
Or in function form:
const isNotNilOrWhitespace = input => (input?.trim()?.length || 0) > 0;
const isNilOrWhitespace = input => (input?.trim()?.length || 0) === 0;
Starting with:
return (!value || value == undefined || value == "" || value.length == 0);
Looking at the last condition, if value == "", its length must be 0. Therefore drop it:
return (!value || value == undefined || value == "");
But wait! In JavaScript, an empty string is false. Therefore, drop value == "":
return (!value || value == undefined);
And !undefined is true, so that check isn't needed. So we have:
return (!value);
And we don't need parentheses:
return !value
I use a combination, and the fastest checks are first.
function isBlank(pString) {
if (!pString) {
return true;
}
// Checks for a non-white space character
// which I think [citation needed] is faster
// than removing all the whitespace and checking
// against an empty string
return !/[^\s]+/.test(pString);
}
I have not noticed an answer that takes into account the possibility of null characters in a string. For example, if we have a null character string:
var y = "\0"; // an empty string, but has a null character
(y === "") // false, testing against an empty string does not work
(y.length === 0) // false
(y) // true, this is also not expected
(y.match(/^[\s]*$/)) // false, again not wanted
To test its nullness one could do something like this:
String.prototype.isNull = function(){
return Boolean(this.match(/^[\0]*$/));
}
...
"\0".isNull() // true
It works on a null string, and on an empty string and it is accessible for all strings. In addition, it could be expanded to contain other JavaScript empty or whitespace characters (i.e. nonbreaking space, byte order mark, line/paragraph separator, etc.).
Meanwhile we can have one function that checks for all 'empties' like null, undefined, '', ' ', {}, [].
So I just wrote this.
var isEmpty = function(data) {
if(typeof(data) === 'object'){
if(JSON.stringify(data) === '{}' || JSON.stringify(data) === '[]'){
return true;
}else if(!data){
return true;
}
return false;
}else if(typeof(data) === 'string'){
if(!data.trim()){
return true;
}
return false;
}else if(typeof(data) === 'undefined'){
return true;
}else{
return false;
}
}
Use cases and results.
console.log(isEmpty()); // true
console.log(isEmpty(null)); // true
console.log(isEmpty('')); // true
console.log(isEmpty(' ')); // true
console.log(isEmpty(undefined)); // true
console.log(isEmpty({})); // true
console.log(isEmpty([])); // true
console.log(isEmpty(0)); // false
console.log(isEmpty('Hey')); // false
I did some research on what happens if you pass a non-string and non-empty/null value to a tester function. As many know, (0 == "") is true in JavaScript, but since 0 is a value and not empty or null, you may want to test for it.
The following two functions return true only for undefined, null, empty/whitespace values and false for everything else, such as numbers, Boolean, objects, expressions, etc.
function IsNullOrEmpty(value)
{
return (value == null || value === "");
}
function IsNullOrWhiteSpace(value)
{
return (value == null || !/\S/.test(value));
}
More complicated examples exists, but these are simple and give consistent results. There is no need to test for undefined, since it's included in (value == null) check. You may also mimic C# behaviour by adding them to String like this:
String.IsNullOrEmpty = function (value) { ... }
You do not want to put it in Strings prototype, because if the instance of the String-class is null, it will error:
String.prototype.IsNullOrEmpty = function (value) { ... }
var myvar = null;
if (1 == 2) { myvar = "OK"; } // Could be set
myvar.IsNullOrEmpty(); // Throws error
I tested with the following value array. You can loop it through to test your functions if in doubt.
// Helper items
var MyClass = function (b) { this.a = "Hello World!"; this.b = b; };
MyClass.prototype.hello = function () { if (this.b == null) { alert(this.a); } else { alert(this.b); } };
var z;
var arr = [
// 0: Explanation for printing, 1: actual value
['undefined', undefined],
['(var) z', z],
['null', null],
['empty', ''],
['space', ' '],
['tab', '\t'],
['newline', '\n'],
['carriage return', '\r'],
['"\\r\\n"', '\r\n'],
['"\\n\\r"', '\n\r'],
['" \\t \\n "', ' \t \n '],
['" txt \\t test \\n"', ' txt \t test \n'],
['"txt"', "txt"],
['"undefined"', 'undefined'],
['"null"', 'null'],
['"0"', '0'],
['"1"', '1'],
['"1.5"', '1.5'],
['"1,5"', '1,5'], // Valid number in some locales, not in JavaScript
['comma', ','],
['dot', '.'],
['".5"', '.5'],
['0', 0],
['0.0', 0.0],
['1', 1],
['1.5', 1.5],
['NaN', NaN],
['/\S/', /\S/],
['true', true],
['false', false],
['function, returns true', function () { return true; } ],
['function, returns false', function () { return false; } ],
['function, returns null', function () { return null; } ],
['function, returns string', function () { return "test"; } ],
['function, returns undefined', function () { } ],
['MyClass', MyClass],
['new MyClass', new MyClass()],
['empty object', {}],
['non-empty object', { a: "a", match: "bogus", test: "bogus"}],
['object with toString: string', { a: "a", match: "bogus", test: "bogus", toString: function () { return "test"; } }],
['object with toString: null', { a: "a", match: "bogus", test: "bogus", toString: function () { return null; } }]
];
I didn't see a good answer here (at least not an answer that fits for me)
So I decided to answer myself:
value === undefined || value === null || value === "";
You need to start checking if it's undefined. Otherwise your method can explode, and then you can check if it equals null or is equal to an empty string.
You cannot have !! or only if(value) since if you check 0 it's going to give you a false answer (0 is false).
With that said, wrap it up in a method like:
public static isEmpty(value: any): boolean {
return value === undefined || value === null || value === "";
}
PS.: You don't need to check typeof, since it would explode and throw even before it enters the method
Trimming whitespace with the null-coalescing operator:
if (!str?.trim()) {
// do something...
}
There is a lot of useful information here, but in my opinion, one of the most important elements was not addressed.
null, undefined, and "" are all falsy.
When evaluating for an empty string, it's often because you need to replace it with something else.
In which case, you can expect the following behavior.
var a = ""
var b = null
var c = undefined
console.log(a || "falsy string provided") // prints ->"falsy string provided"
console.log(b || "falsy string provided") // prints ->"falsy string provided"
console.log(c || "falsy string provided") // prints ->"falsy string provided"
With that in mind, a method or function that can return whether or not a string is "", null, or undefined (an invalid string) versus a valid string is as simple as this:
const validStr = (str) => str ? true : false
validStr(undefined) // returns false
validStr(null) // returns false
validStr("") // returns false
validStr("My String") // returns true
Try this:
export const isEmpty = string => (!string || !string.length);
All these answers are nice.
But I cannot be sure that variable is a string, doesn't contain only spaces (this is important for me), and can contain '0' (string).
My version:
function empty(str){
return !str || !/[^\s]+/.test(str);
}
empty(null); // true
empty(0); // true
empty(7); // false
empty(""); // true
empty("0"); // false
empty(" "); // true
Sample on jsfiddle.
There's no isEmpty() method, you have to check for the type and the length:
if (typeof test === 'string' && test.length === 0){
...
The type check is needed in order to avoid runtime errors when test is undefined or null.

React Conditional Rendering, avoid 0 evaluated to false/undefined

I have checked the other Q/As. Mine is a bit different and I'm new to ReactJS.
Following code for setting const variable evaluates 0 as false/undefined
and value returned from myFunc is "" :
function formatAmount(x){
if(x === undefined || x === null) return "";
return(x.toLocaleString("en-US",{style: "currency", currency: "USD"}));
}
//When user.bill.amount == 0 this line evaluates it to false!!
const amount = user?.bill?.amount || user?.statement?.amount;
function myFunc(){
return(formatAmount(amount));
}
I tried expanding it with a function and IF conditions but the value returned by myFunc is "$NaN":
const amount = () => {
if(user?.bill?.amount || user?.bill?.amount === 0){
return user?.bill?.amount;
}
if(user?.statement?.amount || user?.statement?.amount === 0){
return user?.statement?.amount;
}
}
Expected:
When user.bill.amount == 0, myFunc should return "$0.00"
Actual:
myFunc returns empty string when user.bill.amount == 0
I think the problem here is 0 is falsy so when using || operator 0 will evaluate to false.
const amount = user?.bill?.amount || user?.statement?.amount;
If your environment supports the nullish operator that would work here.
const amount = user?.bill?.amount ?? user?.statement?.amount;

Write a function which takes in a string and returns the counts of each string [duplicate]

This question already has answers here:
Why does javascript's "in" operator return true when testing if 0 exists in an array that doesn't contain 0?
(6 answers)
Closed 3 years ago.
I'm literally stuck at solving this simple question. Anyway I found out another way to solve this but I couldn't figure out the issue with my code.
function charCout(str)
{
str = str.toLowerCase();
var f = {};
for(let i =0;i<str.length;i++)
{
if(str[i] === " ")
{
continue;
}
else{
if(str[i] in Object.keys(f))
{
f[str[i]] += 1;
}
else
{
f[str[i]] = 1;
}
}
}
return(f);
}
input: charCout("my name is Khan23")
expected output: {2: 1,3: 1,a: 2,e: 1,h: 1,i: 1,k: 1,m: 2,n: 2,s: 1,y: 1}
what i got: {2: NaN,3: NaN,a: 1,e: 1,h: 1,i: 1,k: 1,m: 1,n: 1,s: 1,y: 1}
Simply see if the property exists by type coercion like: if(f[str[i]])
function charCount(str)
{
str = str.toLowerCase();
var f = {};
for(let i =0;i<str.length;i++)
{
if(str[i] === " ")
{
continue;
}
else{
if(f[str[i]])
{
f[str[i]] += 1;
}
else
{
f[str[i]] = 1;
}
}
}
return(f);
}
console.log(charCount('the value is 0000'))
You are using the wrong to way to check if key is in object or not.
You can contract your if-else to single line using || operator.
f[str[i]] = f[str[i]] + 1 || 1
It checks whether f[str[i]] already exists or not. If str[i] is not key of f then f[str[i]] will return undefined and undefined + 1 will be NaN.
NaN is a falsy value so NaN || 1 will evaluate to 1.
If the f[str[i]] exists then it will return any number greater than 0 so it will be set to f[str[i]] + 1(incremented by one)
function charCount(str)
{
str = str.toLowerCase();
var f = {};
for(let i =0;i<str.length;i++)
{
if(str[i] !== " ")
{
f[str[i]] = f[str[i]] + 1 || 1
}
}
return(f);
}
console.log(charCount("my name is Khan23"))
Explanation:
You can also use reduce().
const charCount = str => str
.split(' ')
.join('')
.split('')
.reduce((ac,a) =>
(ac[a] = ac[a] + 1 || 1, ac),
{})
console.log(charCount("my name is Khan23"))
using Object.keys(f).includes(str[i]) instead of str[i] in Object.keys(f) is the solution
in operator primarily would work to check if Object provides a particular attribute
Mozilla doc on in and Array.prototype.includes shall help.
following variation of your function would work
function charCout(str)
{
str = str.toLowerCase();
var f = {};
for(let i =0;i<str.length;i++)
{
if(str[i] === " ")
{
continue;
}
else{
if(Object.keys(f).includes(str[i]))
{
f[str[i]] += 1;
}
else
{
f[str[i]] = 1;
}
}
}
return(f);
}
You can take advantage of String.protoype.split and Array.prototype.reduce to solve this. Check the comments in the code for details:
const charCount = s => {
//Create an array of characters found in the string (filtering out spaces)
const chars = s.split('').filter(char => char.trim());
//Use reduce to create an occurrence map - increment by 1 each time a character is encountered
return chars.reduce((accum, char) => {
accum[char] = accum[char] ? accum[char] + 1 : 1;
return accum;
}, {});
};
console.log(charCount("my name is Khan23"))
Thank you all for your helpful suggestions. i finally figured out whats wrong with my code.
inputs and outputs of my defected code is as follows:
input: charCout("my name is Khan23")
expected output: {2: 1,3: 1,a: 2,e: 1,h: 1,i: 1,k: 1,m: 2,n: 2,s: 1,y: 1}
what i got: {2: NaN,3: NaN,a: 1,e: 1,h: 1,i: 1,k: 1,m: 1,n: 1,s: 1,y: 1};
I've used "in" operator to find out whether a specific value of string is present the Object.keys(f) array. That's exactly where I went wrong.
after referring to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in i got to know "in" can't be used to filter array using value at index.
You can use str.split("") to get the list of chars and then do something like
const splitted = str.split("");
const result = {};
splitted.map(letter => result[letter] ? result[letter]++ : result[letter] = 1)
it is just an idea

make a insert function for bracket.js

I'm a making function that replace null by another word/value.
the var in question :
var saveData = {"teams":[[null,null],[null,null]]}
I find out that the variable is a 2D array and to acces a null I shoud do savedata.teams[0][0] so i made a script that modify the variable.
function add(team, data)
{
var str = team.innerHTML;
var str = str.replace(/<td>/g, "");
var text = str.split("</td>");
var i = 0;
while(data.teams[i][0] != null || data.teams[i][1] != null)
{
i++;
}
if( i == data.teams.length - 1){}
if(data.teams[i][0] == null)
{
data.teams[i][0] = text[1];
}
else if(data.teams[i][0] != null)
{
data.teams[i][1] == text[1];
}
$(function() {
var container = $('.creator')
container.bracket({
init: data,
save: saveFn,
userData: ""})
})
}
the result is wierd. it output :
first use :
{"teams":[["team 1",null],[null,null]]}
seconde use :
{"teams":[["team 1",null],["team 2",null]]}
I don't know why, but I suspect the error may come from the while or the if
data.teams[i][0] != null || data.teams[i][1] != null if any of the two value is not null... it move to next element....
its supposed to be:
while(i < data.teams.length)
{
i++;
}
if(data.teams[i][0] == null)
{
data.teams[i][0] = text[1];
}
if(data.teams[i][0] != null)
{
data.teams[i][1] == text[1];
}
Check more into logical operators here.
Logical AND (&&)
Returns expr1 if it can be converted to false; otherwise, returns
expr2. Thus, when used with Boolean values, && returns true if both
operands are true; otherwise, returns false.
Logical OR (||)
Returns expr1 if it can be converted to true; otherwise, returns
expr2. Thus, when used with Boolean values, || returns true if either
operand is true.

Removing numeric values from alphanumeric string

I want to remove all numeric values from a string
But only if the string contains at least one letter.
How can I do this in JavaScript?
For e.g.
var s = "asd23asd"
Then result must be asdasd
However if
var s = "123123"
Then result must be 123123 as the string does not have any letters.
function filter(string){
var result = string.replace(/\d/g,'')
return result || string;
}
or directly
var newString = string.replace(/\d/g,'') || string;
Why || works
the || and & are conditionals operators and sure that you used in if, while ...
If you do somethin like
var c1 = false, c2 = true, c3= false, c4 = true;
if( c1 || c2 || c3 || c4) {
}
This evaluation will stop in the first moment that is valid or invalid.
this mind that the evaluation stop in c2 this mind that is more fast
(true || false) than (false || true)
At this point we can add another concept, the operator return always the last element in the evaluation
(false || 'hey' || true) return 'hey', remember in JS 'hey' is true but '' is false
Interesting examples:
var example = {
'value' : {
'sub_value' : 4
}
}
var test = example && example.value && example.value.sub_value;
console.log(test) //4
var test_2 = example && example.no_exist && example.no_exist.sub_value;
console.log(test_2) //undefined
var test_3 = example.valno_existue.sub_value; //exception
function test_function(value){
value = value || 4; //you can expecify default values
}
You can try this. First check if the word contains any alphabet, if yes then replace.
var s = "asd23asd";
if(/\w+/.test(s))
s = s.replace(/\d+/g, '');
([a-zA-Z]+)\d+|\d+(?=[a-zA-Z]+)
You can try this.Replace by $1.See demo.
https://regex101.com/r/nS2lT4/27
Javascript Code
var txt='asd23ASd3';
if(parseInt(txt))
var parsed=txt;
else
var parsed=txt.replace ( /[^a-zA-Z]/g, '');
console.log(parsed)

Categories