Wednesday, August 23, 2023
HomeProgrammingTrim the Final N Characters from a String in JavaScript

Trim the Final N Characters from a String in JavaScript


Introduction

JavaScript has fairly a number of strategies to control strings. A type of strategies includes trimming the final N characters from a string. This Byte will present you two methods to realize this: utilizing the String.substring() methodology and conditionally eradicating the final N characters.

Utilizing String.substring() to Trim Characters

The String.substring() methodology returns a brand new string that begins from a specified index and ends earlier than a second specified index. We will use this methodology to trim the final N characters from a string. Let’s have a look at how this works with a easy instance:

let str = "Good day, World!";
let trimmedStr = str.substring(0, str.size - 5);
console.log(trimmedStr);

On this code, str.size - 5 is used to calculate the ending index for the substring. This can output:

Good day, Wo

As you may see, the final 5 characters of the string have been eliminated.

Conditional Elimination of Final N Characters

Generally, you would possibly need to conditionally take away the final N characters from a string. This could possibly be helpful while you need to trim characters solely when sure circumstances are met. As an example, you would possibly need to take away the final character from a string provided that it’s a comma.

A technique to do that is with an if assertion:

let str = "Good day, World!,";
if (str.endsWith(",")) {
    str = str.substring(0, str.size - 1);
}
console.log(str);

Within the above code, we used the String.endsWith() methodology to examine if the string ends with a comma. If it does, we take away the final character. This is not a lot completely different than our first instance, besides that it is surrounded by a conditional.

This can output:

Good day, World!

Word: Keep in mind that String.substring() doesn’t modify the unique string. As an alternative, it returns a brand new string. It’s because strings in JavaScript are immutable.

One other solution to do it conditionally is with a regex string and the substitute() methodology:

let str = "Good day, World!,";
let regex = /,$/g;
str = str.substitute(regex, '');

console.log(str); // Good day, World!

This can solely take away the comma on the finish of the string whether it is current.

Conclusion

On this Byte, we explored two methods to take away the final N characters from a string in JavaScript. We realized how one can use the String.substring() methodology, and we additionally checked out how one can conditionally take away characters.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments