Friday 25 November 2016

How to slice string from the end in JavaScript?





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.



11001000000000000001010



110000000001101011100



What would be the way to do this using JavaScript?


Answer



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";
console.log(example.slice(-6));







  • 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: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...