In JavaScript, substitute a blank space within a string with the text "N/A"

Looking to replace any empty spaces in a string with the value "N/A." For example, given an array:

var array= ["value1", undefined, "value3"];
var array2= ["value1", "value2", "value3"];
var array3= ["value1", "value2", undefined];

This is a dynamically generated array so the values can vary. I have 3 instances of arrays with different populated values. My goal is to remove all instances of 'undefined' and replace them with "N/A."

array.toString().replace(/\:''/gi, ": \"N/A\"");
outputs: "value1,,value3"; however, I want it to be: "value1, N/A, value3"

I am struggling with using regex to achieve this. Any suggestions on how to accomplish this?

Answer №1

Avoid regex and opt for the .map method:

let myArray = ["apple", null, "banana"];
const modifiedArray = myArray.map(item => item === null ? 'N/A' : item);
console.log(modifiedArray);

Answer №2

Avoid using regular expressions; instead, opt for utilizing the map function or creating your custom implementation. In this scenario, consider implementing the following code snippet:

for(let element in array) if(array[element] === undefined || array[element] === "") array[element] = "N/A";

Answer №3

A more efficient approach is to utilize Array.prototype.forEach instead of map because the replacement occurs directly within the array.

var arr = ["item1", undefined, "item3"];

arr.forEach((el, ind) => {
    if (el === undefined) {
        arr[ind] = "N/A";
    }
});

console.log(arr);

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

Three.js: Wanting to create objects and add motion along a curved path

In an attempt to create a unique effect, I am exploring the idea of spawning a series of objects on a setInterval and assigning each object a customized animation on a path using requestAnimationFrame. I have successfully added one object and animated it a ...

Decoding the Mystery: What Do the + and # Symbols Mean in Angular 4 Routes?

Check out the repository at https://github.com/AngularClass/angular-starter https://i.sstatic.net/ITi80.png I noticed the use of + and # for referencing within loadChildren and naming conventions in the folder... After consulting the Angular documentati ...

What is the best way to establish a connection between the same port on Expressjs and Socket.io

I am currently using Express.js and Socket.io to develop a chat application. Initially, I created my project with Express-Generator and began by running the node ./bin/www script. However, I decided to remove the ./bin/www file and instead combined it wit ...

Gathering all active session information by utilizing a shared identifier

After dedicating 2 months to this project, I have decided to seek some assistance. My database consists of two tables: Table 1: (Teacher Registration) Code Teacher 1 Smith 2 Allen Table 2: (Student Registration) Code Student Stdpass ...

Oops! It seems like there was a mistake. The ReferenceError is saying that Vue is

I've been working on creating a new app, but I keep running into an issue. Unidentified Reference Error: Vue is not recognized. <template> <v-app> <div id="example-1"> <v-btn v-on:click="counter += 1">Add 1</v-bt ...

The visibility of the Three.js plane is dependent on the mouse being within the boundaries of the browser

Just starting out with three.js and I encountered a strange issue. Whenever the mouse cursor is outside of the content area (for example, if I reload the page and the cursor is on the browser's reload button or outside of the browser window), the obje ...

Performing element-wise division on multiple columns in a NumPy array by a

Can numpy array columns be divided by another 1D column (row-wise division)? For instance: a1 = np.array([[1,2,3],[4,5,6],[7,8,9]]) array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) a2 = np.array([11,12,13]) array([11, 12, 13]) # dividing all rows, b ...

Submit and upload images using POST method in Meteor

I'm just starting out and feeling overwhelmed by the lack of resources on how to upload POST submitted images in Meteor. Is this feature supported out of the box? If not, how should I go about handling it? So far I've broken it down into these s ...

The integration of VueJS with Axios and the Google Maps API

Currently following [this][1] guide to develop a Google Map and now I am looking to execute a GET request with Axios: axios.get("http://localhost:8080/mapjson").then(function(response) { }) in order to integrate the information from my JSON file into the ...

Adjust index starting from 0 in JavaScript

Struggling with setting a consistently unique index that increments by one. Here is an example of my array: const originalArr = [ { name: 'first parent array', childArray: [ { name: '1 / first child' }, ...

Utilizing Vectors in MATLAB

Seeking assistance in creating a vector with dimensions 121x101, where each column is generated by multiplying V_t*e. The calculation for V_t = 1000*10^((i-1)/20), and e represents a column of ones with a length of 121. The challenge lies in varying the v ...

Organizing a collection of objects by their property values

While it may seem like this question has been asked countless times before, there is one unique twist that sets it apart. Let's take a look at the array in question: $array = array( array('name' => 'foo', 'capacity&ap ...

Dealing with popups in nightmarejs: what's the best approach?

Looking for guidance on managing website pop-up windows in nightmarejs. Specifically interested in tasks such as viewing a list of open windows, closing them, extracting data from the pop-ups, and potentially subscribing to popup creation events. Your ins ...

formBuilder does not exist as a function

Description: Using the Form Builder library for react based on provided documentation, I successfully implemented a custom fields feature in a previous project. This project utilized simple JavaScript with a .js extension and achieved the desired result. ...

Trigger an event in Javascript/ASP.net following a dropdownlist selection

On a single HTML page, I have incorporated three dropdown lists for country, city, and district with an initial blank selected value, along with a Google map. The aim is to automatically center and zoom in on the map whenever users make selections from the ...

Fluid zooming and panning capabilities when using a logarithmic axis

I'm having trouble with enabling zoom and panning on a Flot plot with a logarithmic x-axis. Every time I attempt to zoom or pan, all the points on the plot disappear and I need to refresh the page. Below is the link to the jsfiddle where I have the f ...

Exploring the fundamentals of increasing and decreasing counters within a React environment

Hey there, I'm new to React and currently working on an assignment that requires me to change values using increment and decrement buttons. I've managed to do it using the class component approach. However, I have a question regarding the code s ...

Including the file path to an image in a CSS module within a React component from the public directory

I'm currently facing a challenge with adding an image as a background, especially since the image is located in a public folder structure like this: -public -images -image.png -src -assets -components -index.tsx -index.module.css (I want to use the ...

What is the process for showing a table based on a selected value?

I could use some help - I am working on a <select> element with 4 different options in the form of <option>. What I want to achieve is to have tables that are initially not visible, and then when an option is clicked, the corresponding table wi ...

Changing variables from a different file in node.js: a guide

Currently utilizing the discord.js library for my project. Although I can refer to it as such, I am encountering issues when trying to access certain files. For example, let's consider a file named calc.js. In this scenario, I aim to retrieve a var ...