The method .replace() is used to substitute instances within a string

I have set up input fields for users to enter tags.

For example, if a user enters "xyz_DTL_D, John_D" it will be stored in the tagArr[] array.

My goal is to replace the input "_D" with an empty string. So I created the following code:

 var dailycheck = "_D";
   for(var i = 0; i < tagArr.length; i++) {
        if(tagArr[i].indexOf(dailycheck) !== -1){
                        var str = tagArr[i].toString();
                        var finalTag =res.replace("_D" ,"");
                        $scope.tag[i] = finalTag;
                }
        }

The issue is that it replaces "_DTL" as well, which is not the desired outcome.

Desired output: XYZ_DTL , John

Current output: XYZTL_D , John

Is there a way to only replace the expression "_D" and not part of a word starting with _D for all instances?

Any suggestions are appreciated.

Thank you

Answer №1

If the user enters "xyz_DTL_D, John_D "

The expected result will be: XYZ_DTL , John

It appears that you only want to replace the instances of _D that are either at the end of the string or directly before a ,.

Furthermore, it looks like "xyz_DTL_D, John_D " is the output of running tagArr.toString()

You can attempt the following:

var output = tagArr.map( s => s.trim().replace( /(_D)$/, "" ) ).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

I am having difficulty converting the ajax response data stream into a CSV file

I'm trying to convert the ajax response, which contains a stream of data with some unknown characters (possibly a blob, byte stream, or byte array) into a CSV file. However, when I download the file, it still has the same garbled data. $.ajax({ url: ...

Utilizing ng-class to dynamically change glyphicons for sorting a table

I've been encountering some difficulties with implementing the ng-class feature. I have a table that can be sorted in ascending and descending order by clicking on the glyphicon-chevron-down. However, I'm struggling to get it to work properly. M ...

How come when I go back through ajax, my markers always seem to land in the top left corner?

If you incorporate a Google Map on a webpage in http://jquerymobile.com, and navigate away from the page before returning, all the markers will relocate to the top left corner. For instance: This is how my jQuery JavaScript code begins: $('.page-m ...

Using Google App Engine with Python as the back end and AngularJS as the front end is a powerful combination

I am currently working on establishing end-to-end data sharing between GAE using Python and an AngularJS mobile app. The communication is done through JSON as the request body from the mobile app with a contentType set to application/json. Upon checking my ...

Mesh from Three-JS is appearing on the other side of the model

https://i.sstatic.net/yLrC0.png Currently, I am utilizing a custom model created in Blender for my ThreeJS project. After exporting it to a .obj file, I then utilized the Three-js conversion utility to generate a json file. When I set the model to rotate, ...

When using JSON.parse, it may sometimes return [Object Object] instead of the expected

The JSON output of my API looks like this: [{"UserName":"xxx","Rolename":"yyy"}] I am trying to extract the values for Username and RoleName separately using JSON.parse, but it is giving me [Object Object]. Can someone please assist? Your help is much ap ...

What is the best way to have two directives interact with each other?

As a beginner in angular js, I am curious if there is a way for two directives to interact with one another. I attempted to use require: "^mydirective" but strangely, it did not work as expected. ...

Is there an Angular directive that can replicate a mouseenter event?

Is there a way to simulate a mouseenter event with a directive? I have been searching for a directive that can simulate a mouseenter event, but all I have found so far is one that binds a function to mouse over or karma tests for simulating mouse over. W ...

Arrays of lists within massive numpy arrays

While trying to use parts of a large Numpy array, I encountered an issue with Python because the extracted part was identified as a list rather than a Numpy array. Upon investigation, it turns out that Numpy actually stores multiple lists within larger Num ...

Replace the current picture with a newly uploaded one and keep it consistent

On my webpage, there is an image that I want to be able to replace by clicking on it and selecting a new image from the file uploader without showing the upload button. Once the new image is uploaded, I'd like it to replace the current image, and for ...

An issue has occurred with NPM CI where the bindings are not available from watchpack-chokidar2:fsevents

After executing npm ci on GitHub Actions, I encountered the following error: Run npm ci npm ERR! bindings not accessible from watchpack-chokidar2:fsevents npm ERR! A complete log of this run can be found in: npm ERR! /home/runner/.npm/_logs/2021-09-17 ...

Issue with ngModel not being updated within directive

I'm currently working on a directive for a color picker, but I'm having trouble updating the ngModel value. Any suggestions on what might be causing this issue? Check out my code snippet below: .directive('colpkr', [functi ...

Comprehending the intricacies of pointer arithmetic

Currently, I am diving into the world of K&R C. Towards the end, there exists a piece of code demonstrating the usage of fopen. However, one section has left me quite puzzled. #define OPEN_MAX 20 FILE _iob[OPEN_MAX] = { { 0, NULL, NULL, _READ, 0 }, ...

Building a bridge between React Native and MongoLab

I am currently in the process of developing a React Native application for iOS that will require querying a database. After some research, I have chosen to use MongoLab. Upon reviewing MongoLab's documentation, it is suggested to utilize the MongoDB D ...

Choosing specific content from a different div in JavaScript based on the line number

I have a question regarding two div elements, div1 and div2. I am trying to develop a function where in div2, I can specify the line number of div1 and display the relevant content from that specific line. Currently, I have created a function that successf ...

Add numerous submit buttons within a form. Upon clicking on a button, the form should be submitted to a specific URL using AJAX

I have a form with two submit buttons: one labeled as "SUBMIT" and the other as "SCHEDULE NEXT ROUND". When a user clicks on the "SUBMIT" button, the form values should be stored in the database and redirect to the view page. If they click on the "SCHEDULE ...

Change the x and y positions of several div elements as the mouse moves in JavaScript

I am aiming to create a webpage where multiple divs with text and other content move along the x and y axes of the mouse. The desired effect is similar to parallax scrolling, but I have found that existing parallax plugins are image-based and do not work w ...

Sending a reference to the event object within a JavaScript function

There are times when we need to use the event object in JavaScript. Below is an example of how we can pass the event: function test(e){ console.log(e); e.preventDefault(); console.log("You are not going to redirect"); } HTML <a href="www. ...

Load specific options only when needed while maintaining the previously selected state

First off, check out this demo to see what I mean. I have a basic form with a dropdown field. Initially, only one option is pre-loaded and selected. The goal is to load the remaining options when the dropdown is clicked. This functionality works fine, exc ...

Cannot load JSON file from Visual Studio 2013

I am currently working on building a drag-able network diagram using d3.js, and I've come across an unusual issue. Whenever I try to run the page from Visual Studios 2013, I encounter the following error: "Unhandled exception at line 25, column 13 in ...