如何在JavaScript中从最后切片? [英] How to slice string from the end in JavaScript?

查看:71
本文介绍了如何在JavaScript中从最后切片?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个二进制值列表作为不同长度的字符串,但是我需要从每个值中删除最后18个字符。因此,在下面的示例中,粗体是需要保留的。

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.

11001 000000000000001010

11001000000000000001010

110 000000001101011100

110000000001101011100

使用JavaScript执行此操作的方法是什么?

What would be the way to do this using JavaScript?

推荐答案

您必须在 String.prototype.slice()函数中使用负索引。

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


  • 使用负索引作为第一个参数
    将切片的字符串返回到从字符串末尾开始计算的6个元素。

var example = "javascript";
console.log(example.slice(-6)); 


  • 使用负面指数作为第二个参数将切片的
    字符串从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));

如果您想了解有关该功能的更多信息,请访问: https://developer.mozilla.org/en-US / docs / Web / JavaScript / Reference / Global_Objects / String / slice

If you want to read more about that function, visit: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice

这篇关于如何在JavaScript中从最后切片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆