How to slice string from the end in JavaScript? [duplicate]

I have a list of binary values as strings with different lengths, however I need to slice off the last 18 characters from each value. So in the examples below, the bold is what needs to be kept.



What would be the way to do this using JavaScript?

You have to use negative index in String.prototype.slice() function.

  • using negative index as first argument
    returns the sliced string to the 6 elements counting from the end of the string.
var example = "javascript";
  • using negative index as the second argument returns the sliced
    string from 0 to the 6th element counting from the end. It’s opposite to the first method.
var example = "javascript";

console.log(example.slice(0, -6));

In your particular case, you have to use the second method.

console.log('11001000000000000001010'.slice(0, -18));

console.log('110000000001101011100'.slice(0, -18));

If you want to read more about that function, visit:

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   Chrome Fullscreen API

Similar Posts