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

I attempted to create a test scenario to verify that the length of the tasks array is not negative. However, when trying to test this using 'not.toBe' in the code below, an error was encountered

app.js var todos=[]; todos=['to-do one', 'to-do two']; module.exports=todos; app.test.js const todos=require('./app') test('should have a length of at least 0',()=>{ expect(todos.length).toBeGreaterThanOrEqu ...

How can I retrieve the content from an iframe whenever its state is altered using jQuery?

I am currently working on a project where I need to extract the content from a hidden iframe and display it as HTML in a div every time the iframe changes its loading state. The goal is for it to appear as if the page is being redirected and downloading it ...

Unable to make a post using vue.js

I am facing an issue while trying to submit form data using "vue-resource" in my code. The error message I receive mentions a problem with the use of this method alongside vue-cli and vuetify. Error [Vue warn]: Error in v-on handler: "TypeError: this.$h ...

Ways to acquire the reference of the parent component

Within my code, there is a parent component represented as: <Parent> <Child (click)=doSomething()></Child> </Parent> I am looking to establish a reference to the Parent component in order to pass it within a method that will trigg ...

Add the Selected Value to the Title

Is there a way to dynamically add the selected value from each select element to its corresponding heading without requiring user interaction? I need this to happen as soon as the page loads. Here is an example in a jsfiddle https://jsfiddle.net/dqfvyvdt/2 ...

Managing form submissions using Material UI and Next.js

Can someone provide insights on using Material UI with Next Js? I am experimenting with a Login template from Material UI, but I am facing an issue where query params are added to the URL upon Submit. For example: localhost:3000/auth/login changes to: ...

The display of ngtable is not appearing correctly

I recently downloaded the zip file of this plunkr (http://plnkr.co/edit/ISa4xg?p=preview) onto my computer. Upon running the example, I noticed that while the table displays correctly, the CSS styling is not applied properly (e.g. pagination appears in an ...

what is the duration for which a browser stores an ajax response in cache

How can I determine the duration for which a browser caches an ajax response? In Chrome's dev tools network tab, I see that the resource is retrieved from disk cache. Is there a way to know the expiration time of this cached data? The resource being ...

Navigating through sections in NextJS-14: Utilizing useRef for seamless scrolling

In the past, I had developed an older portfolio website using Vite React + TS and implemented useRef for scrolling to sections from the Navbar. Now, my goal is to transition this portfolio to NextJS 14. I transferred my old components and style folders in ...

Is there a way to assign a specific color to individual users in a chat?

I have successfully implemented a chat feature using Pusher, but now I want to customize the appearance by changing the color of the username for the logged-in user when they are active in the conversation. Currently, both my username and another user&apos ...

What is the best way to generate a JavaScript variable using information from SQLite?

I found the examples provided in the JavaScript edition of the Missing Manual series to be extremely helpful! OG.Q. I have explored various options but have not been able to find a solution to my problem yet. This is what I am trying to achieve: Save u ...

Trying to filter out repetitive options in an autocomplete box

Using the jQuery autocomplete plugin, I am trying to display 5 unique search results. Initially, I achieved this by limiting the stored procedure to return only 5 results, but now I want to remove duplicates while still showing 5 distinct results. I'm ...

utilizing props to create a navigational link

How can I display a tsx component on a new tab and pass props into the new page? Essentially, I'm looking for the equivalent of this Flutter code: Navigator.push( context, MaterialPageRoute(builder: (context) => Page({title: example, desc: ...

The `res.send()` function is showing [object object] and I am unable to access any properties

I've just started learning about REST APIs with express. I am encountering a strange issue where the code successfully console logs { name: 'Test', id: 1 } for the user, but when I send the response, it displays [Object object]. Additionally ...

Unsubscribing from a service method in Javascript using RxJS

After clicking a button, a function is triggered to execute. The function includes an method called "executeAction" that retrieves the current view and then passes it as a parameter to another view for future reference. async executeAction(action: ...

Is it possible to verify the presence of an ID with jQuery?

Is it possible to check for the existence of the id 'input-name' before assigning a value to the variable name using a line of code similar to this: var name = $('#input-name').attr("value"); In case the id 'input-name' does ...

Issue with GMap Compatibility on Specific Web Browsers

I'm currently facing an issue with implementing gMap [1] on a website. The map is functioning properly in Chrome and Safari, but it fails to display in Firefox, IE, and Opera (latest versions of all). I have ensured that the Google Map API key loads a ...

Bug Alert: Incompatibility between Angular $resource and PHP causing issues with Update and Delete functionalities

As a newcomer to both AngularJS and PHP, I have been struggling to find comprehensive documentation on using $resource to update records in a database. While I did come across a helpful tutorial here that covers most aspects of $resource usage, I am having ...

After successful login, the user will be automatically directed to the next page with

I am encountering challenges with a specific portion of my code. I am in the process of sending user information to the server, receiving a token from the user, and then aiming to redirect the user to a URL. However, despite the code entering the if stat ...

Intermittent occurrence of (404) Not Found error in the SpreadsheetsService.Query function

Using the Spreadsheet API, I frequently update various sheets. Occasionally, and without any pattern, the SpreadsheetsService.Query function returns a (404) Not Found error. This issue does not seem to be related to internet connectivity or server downti ...