【问题标题】:How to use the Python string index in JavaScript?如何在 JavaScript 中使用 Python 字符串索引?
【发布时间】:2020-10-04 12:32:04
【问题描述】:

在 Python 中,您可以执行以下操作:

string = "Hello World"
print(string[2:5])
# llo

JavaScript 中的等价物是什么?

【问题讨论】:

标签: javascript python string slice


【解决方案1】:

尝试使用slice函数:

var str = "Hello world!"; 
var res = str.slice(2, 5); 
console.log(res) // llo

【讨论】:

  • 可能想要将切片从 2 而不是 0 更改。
  • @Gabip 抱歉编辑文档链接,但 w3schools 不是一个好的参考资源。
【解决方案2】:

您可以同时使用slicesubstring

const str = "Hello world!";

console.log(str.substring(2, 5));
console.log(str.slice(2, 5));

【讨论】:

  • 两者有什么区别?
  • 最小差异...使用子字符串,您可以切换开始/结束顺序并且仍然有效(如果“开始”大于“结束”,它将交换两个参数)。使用切片,您可以使用负数从末尾开始。
猜你喜欢
  • 2015-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-24
  • 2020-01-07
  • 2015-04-23
  • 2013-03-04
  • 2018-07-16
相关资源
最近更新 更多