【问题标题】:How to create a function to remove a string from a string with a starting index and number of characters to be removed [duplicate]如何创建一个函数以从具有起始索引和要删除的字符数的字符串中删除字符串[重复]
【发布时间】:2023-02-02 10:18:23
【问题描述】:

我需要一个函数来从字符串中删除一个字符串并返回原始字符串,其中使用索引开始删除并计算要删除的字符数。

function removeFromString(str, index, count) {
    let char = (count + index);
    (str.slice(index, char))
    console.log (str);
}
``

Im expecting to get the original string returned with the characters indicated removed. I wrote this wrong previously.

【问题讨论】:

  • 在任何情况下你都不会返回任何东西。
  • 你有一些例子吗?

标签: javascript


【解决方案1】:

您需要将结束索引(独占)传递给切片,而不是计数。

function removeFromString(str, index, count) {
    return str.slice(index, index + count);
}
console.log(removeFromString("abcde", 2, 1));
console.log(removeFromString("abcde", 1, 10));

【讨论】:

  • 值得一提的是,在slice(start, end)中,如果使用end >= array.length,则使用array.length
【解决方案2】:

字符串长度属性为您提供字符串中的字符总数。例如。

"String".length = 6

slice 函数切割字符串但索引为 0。因此对于字符串 "String" 0 - 5。如果您的起始索引大于或等于字符串长度,您将得到一个空字符串。您可以查看文档:- Docs 的切片功能。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-30
    • 2013-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多