This post will discuss how to remove the extra delimiter from end of string in JavaScript.

There are several methods to remove the extra delimiter from end of string in JavaScript, depending on what kind of delimiter we want to remove and how we want to handle the whitespace. Here are some of the most common functions that we can use:

1. Using replace() function

One way is to use the built-in function replace(), which function takes a regular expression and a replacement string as arguments and returns a new string that is the result of replacing the matches of the regular expression with the replacement string. We can use this function to remove the extra delimiter from end of string by passing a regular expression that matches the separator and any whitespace after it, and an empty string as the replacement. For example, if we have a string "Hello, world, ", we can delete the extra comma and space at the end using replace() like this:

Download  Run Code

2. Using slice() function

Another way is to use the slice() function, which is also a built-in function of the string object. This function takes one or two arguments: the start index and the end index of the substring to return. It returns a new string that is a part of the original string between the specified indexes. We can use this function to remove the extra delimiter from end of string by finding the index of the last occurrence of the separator and slicing the string before that index. For example, we can use the slice() function with negative indices to delete an extra period from the end of a string:

Download  Run Code

 
Alternatively, we can use the substring() function with the string length to remove one or more characters from the end of a string. The substring() function takes two arguments: the start index and the end index of the substring to be returned. The start index is inclusive, but the end index is exclusive. For example:

Download  Run Code

3. Using trimEnd() function

A third way is to use the trimEnd() function, which returns a new string with whitespace removed from the end of the original string. Whitespace includes spaces, tabs, line breaks, and other characters. However, we cannot use this function to delete any other separators such as commas or periods from the end of the string. For example, we can delete the extra space at the end of a string using trimEnd() like this:

Download  Run Code

That’s all about removing the extra delimiter from end of string in JavaScript.