What is the best way to include a comma following full names within an array?

I have a list containing 150 first and last names that I need to separate by commas in an array. How can I achieve this? Below is my current code, please assist me in inserting a comma after each full name.

var names = $('#namesList').html();
var nameArr = names.split(' ');
// join comma after each full name
console.log(nameArr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id='namesList'>Bhittersweet Angel
    Pam Hankins
    Josh Dena 
    Joanne Deutch 
    Melanie Dodd 
    Randy Scott 
    Bryan Jellick
</p>

Answer №1

let userNames = $('#namesList').html();
let cleanUserNames = userNames.trim().split('\n').map((name) => name.trim()).join(', ');
console.log(cleanUserNames);
  • The HTML content of the names list is extracted and trimmed to remove unnecessary newlines using trim().
  • The cleaned content is then split into an array based on newline characters: split('\n').
  • Each element in the array is iterated over using map to trim any leading or trailing spaces.
  • Finally, the processed array is joined back into a single string with elements separated by commas: join(', ').

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

Netlify Hosting Experiences Endless Loading Loop on Redirected Custom 404 Page

My website, which is built on React.js and can be found at aritraroy.live, is hosted on Netlify. I wanted to enhance the user experience by creating a custom 404 error page for my site, as the default one provided by Netlify was not satisfactory to me. I f ...

The dependencies were not updated after running `npm install`

When attempting to update the dependencies in my react-native CLI app by running npm install for the package.json, I encountered issues. Subsequently, I tried using npm audit fix and npm audit fix --force without success. In an effort to resolve the probl ...

Using two variables for iteration in Vue.js v-for loop

Can you create a v-for loop with two variables? I attempted the following, but it did not function as expected <ul id="example-1"> <li v-for="apple in apples" v-for="banana in bananas"> {{ apple .message }} {{ banana .message }} & ...

What causes Armadillo to lag behind a C-style array in a basic row-oriented computational task?

Presently, I am performing computations on a small quantity for each value within a large matrix (millions of rows, less than 1000 columns) while treating each row independently. To elaborate further, for every value M(i,j) in each row i, column j of this ...

Windows users can rely on auto-saving, but Mac users may need to find another solution

I tried the solution provided in this discussion thread (Saving without dialog window) to save an image as PNG without triggering the 'Save as..' dialog. It worked perfectly on my Windows computer. However, when I shared the script with my collea ...

Incorporate a file into all API endpoints with Next.js API functionality

Is there a way to incorporate a "bootstrap" file (a file with side-effects) as the first file included in all Next.js APIs? The main issue is that I have a Winston logger in a file that needs to be added to every API endpoint, but this process hinders dev ...

Trying to add an item to a TypeScript nested array causes an issue: unable to access property 'push' because it is undefined

For a while now, I've been searching on SO trying to find a solution to my issue. It seems that my code isn't as simple as just "push object into array." In my interface, I have a "Year" property typed with another interface as an array: exp ...

Caution: Prop type validation failed: The `open` prop in `ForwardRef(Modal)` is designated as required, yet its value is currently `undefined`

After implementing code from Material UI Dialog component, I am receiving a warning. Although the application functions properly, I am seeking a solution to resolve this warning. Can anyone provide guidance on how to address it? To access the Material UI ...

The failure of jQuery AJAX error callback to execute

I'm currently facing an issue with an AJAX call that I have in my code. Here's the code snippet: $.ajax({ type: "get", url: "xxx.xxx.xxx/xxx.js", dataType: 'jsonp', success: function(data) { ...

issues with jquery on function malfunctioning

I have some jQuery code that I'm struggling with $(".delete").on('click', function (e){ e.preventDefault(); var id = $(this).prop('id'); console.log('Delete button id: '+id); var formWrapper = $(".form-wr ...

Drawing recursive 2D tree fractals using WebGL technology

Attempting to create a binary fractal tree in webgl, but struggling with the branch angles not aligning as desired. The approach involves plotting vertex points into an array, converting it into a float32array, and then utilizing drawArrays(LINE_STRIPE) fo ...

Tips for maintaining the selected radio button state after refreshing the JSP page: Ensuring that the radio button remains selected

I need help with refreshing a page after clicking on one of two radio buttons. I've tried multiple solutions but haven't been successful so far. Can someone assist me? <script> $(document).ready(function() { $(document).on('c ...

Using AJAX to send an Authorization header on a BlackBerry device

For my ajax call, I have been attempting to set the Authorization header. While it works perfectly fine in all browsers, it seems to be causing trouble on Blackberry 4.6. Has anyone else encountered this issue and found a solution? It's quite frustra ...

What is the most effective method for refreshing a control following an Ajax request?

I am currently working on a website that sends an Ajax request to save data to a database. I would like to update the webpage to show the user that their changes have been successfully submitted. I have brainstormed three possible solutions: Immediately ...

Using data across multiple instances in node.js EJS partials

I need some advice regarding my nodejs project. I have created a sidebar partial that requires user data to be displayed on it. This sidebar is utilized across multiple pages in the project. However, currently, I have to include the user data in every func ...

Accessing state in Vuex modules is crucial for managing and manipulating data effectively

Feeling a bit lost here... I'm utilizing Vuex in my project and have a module called common stored in the file common.js: const initState = { fruits: [] } export default { state: initState, mutations: { SET_FRUITS(state, fruits) { cons ...

Removing the popover feature from a jQuery FullCalendar

I came across a sample that is very similar to mine, and I am looking for a way to hide the popover when I click anywhere on the screen. Is this possible? If so, how can it be achieved? $.fn.popover.defaults.container = 'body'; $('#mycalen ...

Code snippet for displaying rotating messages. Unsure of the proper syntax to use

The header serves as a prime example For quite some time, I've been attempting to create a header similar to the one on this portfolio. It allows for different comments to appear on the same line when clicking an arrow without any refreshing. It&apos ...

The error message "a.lat is not a function" is indicating a problem with the

As I was working on a code to extract data from a CSV file using a split function as the separator, and then calculate the distance between two sets of input coordinates, I encountered an error message stating "a.lat is not a function." Despite searching o ...

Determine whether the user has scrolled past a specific threshold

Is there a way to display the button with the id backtotop only when the user has scrolled more than 250 pixels? This is my code: <template> <div> <button v-if="checkScroll" class="goTop" @click="backToT ...