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?
The slice() method extracts a part of a string. The slice() method returns the extracted part in a new string. The slice() method does not change the original string. The start and end parameters specifies the part of the string to extract.
Javascript splice is an array manipulation tool that can add and remove multiple items from an array. It works on the original array rather than create a copy. It 'mutates' the array. It doesn't work with strings but you can write your own functions to do that quite easily.
JavaScript has a built-in slice() method by using that we can make a copy of a string. Similary, you can also do it by assigning the old string to a new variable.
The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end ( end not included) where start and end represent the index of items in that array.
You have to use negative index in String.prototype.slice()
function.
var example = "javascript"; console.log(example.slice(-6));
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With