Get rid of the unnecessary vertical line that is located at the end of the string

I have come across a situation similar to the one demonstrated in this code snippet: http://plnkr.co/edit/eBjenGqgo3nbnmQ7XxF1?p=preview

Currently, I am working with AngularJS 1.5.7. The directives used in my input - ( first ) textarea are the same as those shown in the Plunkr example (ng-list, ng-trim...). However, my output is displayed within a different ( second ) textarea, but the underlying logic remains quite similar. $scope.outputValue represents an array that I am converting to a string and then applying a RegExp pattern to:

$scope.outputValue  =  $scope.outputValue.toString();
$scope.outputValue  =  $scope.outputValue.replace(/,/g, " | ");

The issue I am facing is that the resulting string consistently adds an additional " | " at the end. Oftentimes, the output appears like this when a user enters multiple empty array items in the first textarea:

var foo = "one | two | three | four | | | | |";

However, what I really want to display is:

var foo = "one | two | three | four";

The primary objective here is to eliminate all the "|" characters that are appended to the end of the string as replacements for ','. Nonetheless, it should be noted that the output may contain "|" values as well. Therefore, an output like this would also be valid:

var foo = "one| | ||two| | three| | four||";

A similar issue can be observed in the Plunkr example, where empty array items are generated and separated by commas.

Is there a RegExp solution that could help address this problem?

Answer №1

Instead of using the toString() and .replace() methods on an array, try utilizing the .join() method instead.

   function convertToString(stringArray) { 
       return stringArray.join(" | ");
   };

  //example: names = ["morpheus","neo","trinity"] 
  //output will be: morpheus | neo | trinity

Check out the DEMO on PLNKR


If no value is provided in the array items, this method may still output vertical bar characters at the end.

To address this issue, you can add a filter to remove items that consist only of white space:

  function convertToString(stringArray) {
       var filteredArray = stringArray.filter((s)=>(s.trim()));
       return filteredArray.join(" | ");
   }

See the updated DEMO on PLNKR.

Answer №2

Utilizing regular expressions is the key.

 var bar = "one | two | three | four | | | | |";
 bar = bar.replace(/(\s?\|)+$/g, '');
 console.log(bar); //one | two | three | four

Discover more about regular expressions in javascript here.

MDN Regular Expressions

MDN String.prototype.replace()

Answer №3

Consider utilizing the slice method in this manner:

bar = bar.slice(0,-1)

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

What could be the reason for Angular to merge the element at index 0 of an array into a subarray instead of doing

After setting up the Array in my oninit function, I encountered an issue where one part of the array was functioning as intended while the other returned an error. this.tests = [{ status: 0, testresults: [{ name: 'test ...

Challenges with creating a contact form using bootstrap modal

I'm facing an issue with a bootstrap modal contact form. It works fine on all browsers except for iPad/Safari. Can anyone help me figure out what's wrong? On iPad, the modal is positioned to the right and down the page instead of in the cente ...

Enabling automatic scaling during the rendering of an .stl file using three.js

I'm in the process of developing a server/webpage with the following functionality: Users can upload an .stl file to be 3D-printed The server executes a mesh repair script on the uploaded .stl file The corrected .stl file is displayed in the user&ap ...

How to include a javascript file in a different file and compile it using Node.js

For running my practice JS files, I rely on Node. As an example, I use node bts.js. In order to implement a queue, I decided to install Collections by using the command npm install collections --save. You can also see this reflected in the hierarchy shown ...

The location of errors is not displayed in VueJS stack traces

My Current VueJS Setup Check out the Source Code here I am working on a project using VueJS with webpack. I have chosen not to use the vue-loader plugin or .vue files. My project structure resembles a typical Javascript webpack project where I import vu ...

Issues with GTM web tracking due to conflicts with the jQuery submit function when used in an AngularJS form

I am having trouble getting the Google Tag Manager jQuery script to fire when tracking form submissions. I have removed any AngularJS expressions for privacy reasons. Can anyone provide assistance with this issue? <div id="login_signIn" class=""> ...

Incorporate extra padding for raised text on canvas

I have a project in progress where I am working on implementing live text engraving on a bracelet using a canvas overlay. Here is the link to my code snippet: var first = true; startIt(); function startIt() { const canvasDiv = document.getElement ...

AngularJS: Transforming form field inputs into JSON format

I am curious about how I could create a function (either a directive or controller) that can convert all of my form inputs into JSON, including their current values. The JSON format I have in mind is something like this: { fields: [ {fi ...

React - Issue with Input event handling when utilizing both onChange and onKeyDown functions

I was attempting to create a feature similar to a multi-select, where users could either choose a value from a list or enter a new value. The selected value should be added to an array when the user presses the enter key. To monitor changes in the input ...

Is it possible to shift the image within the <canvas> element without having to redraw the entire canvas?

I created a game board and I am trying to implement drag-and-drop functionality for my pieces, which are in .gif format. However, I am struggling with finding a solution that allows me to move the pieces without constantly redrawing the entire board. Cur ...

Adjust css style based on the current time of day

I recently came across this fascinating tutorial that demonstrates an animation changing from day to night every 30 minutes. The concept is very appealing, but I began contemplating how to adapt this animation to reflect real-time changes between day and ...

Simple Angular directive for generating pie charts

Having some trouble integrating the jQuery plugin called "easy pie chart". Has anyone successfully accomplished this before? My goal is to create a directive from this plugin, but I've run into some issues in my attempts so far. Here are the differe ...

Issues arise when trying to integrate iframes with Ionic and AngularJS, as they

Using iframes in my ionic app to display webpages within the application has presented a challenge. This is what I currently have implemented: <iframe class= 'webPage' name= "eventsPage" ng-src="{{object.url}}"></iframe> The issue ...

Creating a streamlined system for building and deploying an angularjs/asp.net web api

Looking to streamline the deployment process for my AngularJS app and C# WebAPI. The Angular app repo is stored in stash, while the C# REST API is in TFS. Is it feasible to set up an automated build and deployment system for this setup? What options are ...

Cookies or Services: A Debate on the Best Practices for Storing Cart IDs

Technology Stack: React Node.js Choice 1: Upon receiving a request for "/", the server generates a cart in the database and saves the id in a cookie. Angular fetches the id from the cookie to use it in managing the cart. Whenever a purchase is made, t ...

Dynamic Interactive Content with AJAX

Imagine if all the forms in your application followed this structure: <div id="result_messages"></div> <form action="/action"> <!-- all the form --> </form> Here's an example of what a submit button for this form might ...

What is the best way to hide the div when scrolling to the top?

Is there a way to hide the circle once it's scrolled to the top? Currently, I can scroll the circle to the top but it remains visible. Upon further exploration, I found that clicking on the circle scrolls it to the top and then on a second click, it f ...

Is nested testing the key to an elegant JQuery/AJAX form validation solution?

As I implement form validation with JQuery/AJAX, my goal is to provide a seamless experience for users. When an entry is missing or incorrect, I aim to display a single alert message and return the user to the form so they can make adjustments and resubmit ...

Setting a checkbox to true within the MUI Data Grid using my input onChange event - how can I achieve this?

I am looking to highlight the selected row in my usage input onChange event. https://i.stack.imgur.com/rp9rW.png Details of Columns: const columns = [ { field: 'part_code', headerName: 'Part Code', width: 200 }, { ...

Determine the total quantity of colored cells within a row of an HTML table and display the count in its own

I need assistance with a table that has 32 columns. From columns 1 to 31, I am able to fill in colors by clicking on the cells. However, I now want to calculate and display the number of cells that are not colored in the last column. This task must be co ...