I have this data in variable
Names : "Amit Singh, Kumar Anand"
Names : "Ashish Singh"
this can be single name or multiple names seperated by commas "James, Anand, xyz,..."
In for loop
<div *ngFor="let user of Info">
{{ (user.Names != null && user.Names.length>0) ?
(user.Names |
slice:0:1)
: '' }}
</div>
Here we get output only A but i want AS if comma is not present otherwise if comma is present (i.e. multiple names are there) i want to display M in place of first name and last name
Any solution Thanks
You can do the following if you want it in 1 line;
user.Names.split(",").length === 1 ?
user.Names.trim().split(" ").map(x => x[0])
.reduce((acc, curr) => acc + curr)
: 'M'
Related
I want to write a ternary statement which if true returns a string with a colon at the start, e.g. 'Desk One: Test booking' else I just want to return the desk name, e.g. 'Desk One'.
Currently my ternary looks like this
${deskName} ${bookingName ? bookingName : ''}
I have tried the following with no success
${deskName} ${bookingName ? ':'bookingName : ''}
${deskName} ${bookingName ? \":\"bookingName : ''}
What you did was almost what you needed, here:
${bookingName ? `:${bookingName}` : ''}
You could also do:
${bookingName ? ':' + bookingName : ''}
We can use the ternary operator to conditionally add a : before the contents of bookingName, if it isn't empty, otherwise, just add a empty string
const deskName = 'Desk One'
let bookingName = 'Test booking';
console.log(deskName + (bookingName ? `: ${bookingName}` : ''));
// Desk One: Test booking
bookingName = '';
console.log(deskName + (bookingName ? `: ${bookingName}` : ''));
// Desk One
Having some issue with nested ternary :
I have code :
var genericName = Beauty;
setTitle = (!empty(shopOnline) ? shopOnline + ' | ' : '')
+ (!empty(productName) ? productName + ' | ' : '')
+ genericName;
I want scenario like:
if genericName is not empty - Shop Online | Product Name | Generic Name
if genericName is empty - Shop Online | Product Name
Currently I am getting the output of my code (if genericName is empty) - Shop Online | Product Name |
How we can add the nested ternary operator to remove " | " if genericName is empty after Product Name
( (!empty(productName) ? productName + ' | ' : '') )
Using filter() and join()
[shopOnline, productName, genericName].filter(Boolean).join(' | ')
Here Boolean function is given as a callback to filter out the falsy values like
0, -0, null, false, NaN, undefined, ''
You can also use your empty() as filter's callback
[shopOnline, productName, genericName].filter(i => !empty(i)).join(' | ')
const ticket = {
movie : document.getElementById("movie").value,
amount : document.getElementById("amount").value,
};
This is my object and I want to validate input. But I'm not sure how to change if-else statements to one switch case, since it has different statements.
PS: for learning purpose I need to use javaScript and not jQuery.
if(ticket.movie ===""){
document.getElementById("warningMovie").innerHTML = "need to choose a movie"
}else{
document.getElementById("warningMovie").innerHTML = "";
}
if(ticket.amount === ""){
document.getElementById("warningAmount").innerHTML = "need to choose amount"
}else{
document.getElementById("warningAmount").innerHTML = "";
}
Something like this?
I am using Object.entries and
a Conditional operator (ternary) twice :)
and add the key of the object to the ID of the span - I could use warningAmount but then I would have to capitalise the key
Note the object could have been created by looping over input elements
Also ignore ("aeiou".indexOf(item[0].toLowerCase())>=0?"n ":" ") if you do not like it
const ticket = {
movie: "",
amount: 0,
snack: "Chips",
};
for (let [key, value] of Object.entries(ticket)) {
document.getElementById("warning_" + key).innerHTML =
value ? "" :
"need to choose a"+ ("aeiou".indexOf(key[0].toLowerCase())>=0?"n ":" ") + key
}
<span id="warning_movie"></span><br/>
<span id="warning_amount"></span><br/>
<span id="warning_snack"></span><br/>
I would use ternary operator in this case. Eg.:
document.getElementById("warningMovie")
.innerHTML = ticket.movie ? "" : "need to choose a movie"
I did this code :
var fs = require('fs');
var str = fs.readFileSync('input.txt', 'utf8');
str.split(/\s+/).forEach(function (s) {
return console.log(
s === 'bob'
? 'boy'
: s === 'alicia'
? 'girl'
: s === 'cookie'
? 'dog'
: 'unknown');
});
But in my input file there are some space, and I don't want my code to take it into account. My input file is :
cat
bob
alicia
shirley
cookie
thomas
rat`
So how can I code, to ignore the space in my input file please ?
First of all if you'd console.log(str.split(/\s+/)) you'll get
[ 'cat', 'bob', 'alicia', 'shirley', 'cookie', 'thomas', 'rat`' ]
so as everyone has already said /\s+/ will in fact remove the spaces
#JuanCaicedo your solution doesn't work well sorry, I tried and between cookie and thomas there are space, and the code write unknown. The result is unknown boy girl unknown dog unknown unknown unknown so after rat the code take care about the space
the output you're seeing is correct, according to your logic
s === 'bob'
? 'boy'
: s === 'alicia'
? 'girl'
: s === 'cookie'
? 'dog'
: 'unknown');
If the string doesn't equal bob or alicia or cookie it will output unknown therefore
cat = unknown
bob = boy
alicia = girl
shirley = unknown
cookie = dog
thomas = unknown
rat` = unknown
Please look at the code below
function removeEmptyLines(str) {
const arrayOfLines = str.split("\n"); // Remove empty lines from the string which leaves "" in the returned array
const filtered = arrayOfLines.filter(line => line !== ""); // filter the array and remove all the empty strings
const joined = filtered.join(" "); // form a single string
return joined; // return filtered array
}
I want to put two values or data into my span. I am putting value into span like this:
$('#spanid').text(data[i].phonenumber);
the code above will put the phone number to the span now I want to make it in a way that if the data has another number like mobile number i will add it to the text if available. I put it like this:
$('#spanid').text(data[i].phonenumber|| data[i].mobilenumber);
But only the first value is set even if there is a value for mobile number.
Any idea is appreciated
Do you want something like this
$('#spanid').text((data[i].phonenumber ? data[i].phonenumber +" , " :"") + " " +(data[i].mobilenumber? data[i].mobilenumber :"" ))
and you can also shorthand the second condition
$('#spanid').text((data[i].phonenumber ? data[i].phonenumber +" , " : "") + " " +(data[i].mobilenumber || "" ))
|| condition for both object will return only first object if it has value to it. If you wish to use it as separator, you need to concatenate it in both data and then set it to span:
$('#spanid').text(data[i].phonenumber +"||"+ data[i].mobilenumber);
The further answers are MAYBE working, but concatinating strings like that is very slow, better don't do so.
Concatinating a strings is fastest like this:
[string1, string2].join('')
You don't need any operator like || to add in text. Just add-
$('#spanid').text(data[i].phonenumber +""+ data[i].mobilenumber);
So, if any one is present, it will be available in text. Or if both are present it will be in appended form
Fiddle : http://jsfiddle.net/1oo4noed/
With your code the mobile number would only be displayed if there is no phone number. Try it with
$('#spanid').text((data[i].phonenumber || '') + (data[i].phonenumber && data[i].mobilenumber ? ", " : "") + (data[i].mobilenumber || ''));
You can do this by adding a the + operator in the text(); function to concatenate the strings:
$('#spanid').text(data[i].phonenumber + data[i].mobilenumber);
For putting both of the values within the text() function, with checking if they exist, i'd do something like this:
$('#spanid').text((data[i].phonenumber == "" ? "" : data[i].phonenumber) + (data[i].mobilenumber == "" ? "" : data[i].mobilenumber));
In your data object
var data={
phonenumber:222222222,
mobilenumber:''
};
If phonenumber or mobilenumber is missing it should have empty string, null or undefined to identify value exist or not.
Assuming if phonenumber or mobilenumber is missing it will have empty string
var data={
phonenumber:222222222,
mobilenumber:''
};
var text = '';
if(data.phonenumber !='' && data.mobilenumber !='' ){
text = data.phonenumber +','+ data.mobilenumber;
}
else if(data.phonenumber == ''){
text = data.mobilenumber;
}
else{
text = data.phonenumber;
}
$('#spanid').text(text);
Demo