Combining a name using JavaScript even if certain parts are not available

How can I efficiently combine name elements without any extra white space in Vue.js?

let FirstName = "John"
let MI = "G"
let LastName = "Jones"
let Suffix = "Jr."

I want to create let fullName = "John G Jones Jr."

However, in cases like this:

let FirstName = "John"
let MI = "" or null
let LastName = "Jones"
let Suffix = "" or null

I aim for let fullName = "John Jones" without any additional white spaces.

Simply concatenating with spaces will not suffice. Is there a more elegant solution than using multiple if statements?

Considering the constraints of working within a Vue.js environment and not being able to rely on jQuery.

Thank you

Answer №1

To efficiently handle this situation, consider storing the values in an array and then filtering out any falsy values before joining them with a space delimiter.

let firstName = "John",
  middleInitial = "",
  lastName = "Jones",
  suffix = null,
  fullName = [firstName, middleInitial, lastName, suffix].filter(value => value).join(' ');

console.log(fullName)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unfortunately, I am unable to transmit a cookie using the res.cookie method in Express

After setting up the route to send a JWT with a cookie, I'm unable to see it in my browser. Here's the code for the route: router.post('/signup', async (req, res) => { const { email, password } = req.body try { const ...

Chromium is having issues with updating the dynamic source attribute

One portion of my script that pertains to the question is as follows: <script type="text/javascript> function handleImageClick() { var image = $("#image_id"); $(image).attr("src", "ajax-loader.gif"); $.ajax({ ...

Preserve marked checkboxes upon page refresh

So I created a search engine with a filter using checkboxes in a form. The filter function is working fine when I submit the form (I'm using Flask for this). However, once the results are displayed, the checkboxes that were used as filters become unch ...

Arranging JSON data by a specific attribute using JavaScript

As someone who is new to JavaScript, I have been working on some basic exercises. In my current code, I have a JSON data stored in a String that contains information about employees. My goal is to sort this data based on the age attribute and display the o ...

What is the process of initializing divs in DataTables?

My application has a DataTable installed, but I encountered an error message stating "DataTables warning: Non-table node initialisation (DIV). For more details about this error, please visit http://datatables.net/tn/2". I'm aware that DataTables is d ...

What are the best ways to customize exported and slotted components in Svelte?

Is there a similarity between Svelte slots and vanilla-js/dom functionality (I'm having trouble with it). In html/js, I can achieve the following: <style> body {color: red;} /* style exposed part from outside */ my-element::par ...

Attempting to iterate over the array of objects in order to discover a match

I am currently working with an object structure that resembles the one shown in the image linked below. My goal is to compare the inner object properties (such as massing type id) with existing IDs. If there is a match, I want to retrieve the name of that ...

Tips for activating just a single event, whether it's 'change' or 'click'

I am facing an issue with a number input tag that has two event listeners 'on-click' and 'on-change'. Whenever I click on the arrow, both event listeners get triggered. I want only one event to trigger first without removing any of the ...

Secure an input field for exclusive attention. React

How can I lock the focus of my input field? I attempted using the following code: onBlur={this.click()} However, it was not successful. What is the correct way to accomplish this? ...

Discovering the variable name that holds the maximum number following the usage of Math.max()

Let's assume we have the following variables set: var number1 = 48; var number2 = 420; var number3 = 39; If we want to determine the highest value among them, we can use: let maximumValue = Math.max(number1, number2, number3); What if we want to kno ...

What are some more efficient methods for implementing page location detection with Angular directives?

My website currently features a navigation bar with 4 anchor links that direct users to different sections of the page. As you scroll down the page, the corresponding link on the nav bar lights up to signify your position on the site. Experience it yourse ...

Issue with Angular Factory not being invoked

I am currently using a tutorial to create a MEAN app with Google Maps. However, I have encountered an issue where the map is not appearing on the page. Surprisingly, there are no errors in the browser console and even when debugging with node-inspector, I ...

Encountering an NPM ELIFECYCLE error when attempting to start the node server with the

After following the instructions on deploying test-bot on IBM Watson from this link https://github.com/eciggaar/text-bot, I encountered errors while attempting to deploy the code locally using CLI foundry. My setup includes Node.js version 6.10.3 and npm ...

Using a dojo widget within a react component: A beginner's guide

Has anyone found a way to integrate components/widgets from another library into a react component successfully? For example: export default function App() { const [count, setCount] = useState(0); return ( <button onClick={() => setCount(count + ...

Is it possible to assign multiple ID's to a variable in jQuery?

I am currently using a script for a slider known as Slicebox, and in order to have different image sizes for mobile and desktop views, I need to duplicate the feature on my website. Although it's not ideal, I really like this slider and want to explo ...

Error encountered: Unable to assign onClick property to null object

Hey everyone, I'm running into an issue with my JavaScript. It keeps throwing a TypeError: Cannot set properties of null (setting 'onclick') at SignUp.js:4:43 <HTML> <body> <div class="input-box"> <span class="deta ...

Identify and forward to the mobile-friendly version of the site

I am currently working on a website that requires separate files for mobile view as the html layout poses challenges in making it responsive. My goal is to find code that can detect if the user is accessing the site from a mobile device, and automatically ...

Automating the selection of a drop down based on a condition in Angular 2: A step-by-step guide

I'm facing an issue with a drop-down menu where no default value is selected. On my homepage, I need to automatically select an option based on query parameters. I've attempted various methods but none have been successful. Below is the code snip ...

Design a dynamic top navigation bar in Angular or any other framework that automatically adjusts to the size of the screen, similar to the responsive bookmarks bar in

Could you offer guidance or suggestions on how to design a navigation bar (using Angular 1, jQuery, CSS, etc) that emulates the functionality of Google Chrome bookmarks bar when resizing the page? Essentially, as the page size decreases, a new button/symbo ...

I'm looking to create a Vuex getter to retrieve data from the Google API documentation – can you help

Can someone help me figure out how to create a getter in Vuex store with flat data from the Google Docs API? My goal is to extract the textRun content and store it in an array because there will be multiple messages. Currently, I have hard coded this respo ...