如何在 JavaScript 中从末尾切片字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42308976/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to slice string from the end in JavaScript?
提问by Graeme
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.
我有一个二进制值列表,作为具有不同长度的字符串,但是我需要从每个值中切出最后 18 个字符。所以在下面的例子中,粗体是需要保留的。
11001000000000000001010
11001000000000000001010
110000000001101011100
110000000001101011100
What would be the way to do this using JavaScript?
使用 JavaScript 执行此操作的方法是什么?
回答by kind user
You have to use negative index in String.prototype.slice()function.
您必须在String.prototype.slice()函数中使用负索引。
- using negative index as first argument returns the sliced string to the 6 elements counting from the end of the string.
- 使用负索引作为第一个参数将切片字符串返回到从字符串末尾开始计数的 6 个元素。
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.
- 使用负索引作为第二个参数返回从 0 到从末尾计数的第 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
如果您想了解有关该功能的更多信息,请访问:https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice

