【问题标题】:javascript remove a exact index character from the string [duplicate]javascript从字符串中删除一个精确的索引字符[重复]
【发布时间】:2021-08-30 08:20:12
【问题描述】:

let test = 'This is the test string';

console.log(test.substr(3));

console.log(test.slice(3));

console.log(test.substring(3));

这些方法正在删除前 3 个字符。但我只想从字符串中删除第三个字符。

日志必须是:'这是测试字符串'

İ如果你帮助我,我会很高兴。所有示例都是从 substr 中给出的,例如 slice。例如。有什么不同的方法吗?

【问题讨论】:

  • test.slice(0,2) + test.slice(3)

标签: javascript


【解决方案1】:

const test = 'This is the test string';
const result = test.slice(0, 2) + test.slice(3);
console.log(result);

您可以通过使用.slice() 连接字符串的两个部分来实现此目的。

【讨论】:

  • test.length 可以被删除,因为slice 具有str.length 作为默认结束参数。
  • 无需在第二个.slice 调用中添加第二个参数。默认情况下,当没有提供第二个参数时,它将切片到字符串的末尾:)
【解决方案2】:

首先,获取第一个3 字符,然后添加字符4-end,连接它们以获得所需的结果:

let test = 'This is the test string';

let res = test.substr(0, 2) + test.substr(3);

console.log(res);

由于substr 使用以下参数

substr(start, length)

开始要包含在返回的子字符串中的第一个字符的索引。

长度 可选。要提取的字符数。
如果省略长度,substr() 会将字符提取到字符串的末尾

我们可以使用test.substr(3)从第3个字符到最后一个字符而不指定字符串的长度

【讨论】:

    【解决方案3】:

    您可以使用 substring 方法并连接字符串来实现它

     str = "Delete me ";
     function del_one_char(string , removeAt){
          return string.substring(0, removeAt) + string.substring( removeAt + 1, string.length); 
     }
      console.log(del_one_char(str , 2))
      // result one character at 2nd position is deleted
    

    【讨论】:

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