Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 287
Gazz Avatar asked Feb 17 '17 23:02

Gazz


People also ask

How do you slice a string from the end?

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.

Can you SPlice a string JavaScript?

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.

How do you clone a string in JavaScript?

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.

What is the slice method in JavaScript?

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.


1 Answers

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

like image 57
kind user Avatar answered Sep 16 '22 14:09

kind user