删除字符串中某个位置的字符-javascript

这个问题已经在这里有了答案:

  • 如何使用Javascript从字符串中删除字符?                                     17个答案

有没有一种简单的方法可以删除javascript中某个位置的字符?

例如 如果我有字符串"Hello World",是否可以删除位置3处的字符?

我要寻找的结果将是以下内容:

"Helo World"

这个问题不是Javascript的重复-从字符串中删除字符,因为这是关于在特定位置删除字符,而这个问题是关于删除字符的所有实例。

starbeamrainbowlabs asked 2020-01-10T20:56:37Z
8个解决方案
77 votes

这取决于您使用以下简单String方法(在本例中为slice())找到以下内容的难易程度。

var str = "Hello World";
str = str.slice(0, 3) + str.slice(4);
Matt answered 2020-01-10T20:56:56Z
13 votes

你可以这样尝试!

var str ="Hello World";
var position = 6;//its 1 based
var newStr = str.substring(0,position - 1) + str.substring(postion, str.length);
alert(newStr);

这是实时示例:[http://jsbin.com/ogagaq]

Ishan Dhingra answered 2020-01-10T20:57:20Z
6 votes

如果省略特定的索引字符,则使用此方法

function removeByIndex(str,index) {
  if (index==0) {
      return  str.slice(1)
  } else {
      return str.slice(0,index-1) + str.slice(index);
  } 
}

var str = "Hello world", index=3;
console.log(removeByIndex(str,index));

// Output: "Helo world"
SURENDRANATH SONAWANE answered 2020-01-10T20:57:40Z
5 votes

将字符串转换为数组,在指定的索引处剪切一个字符,然后返回字符串

let str = 'Hello World'.split('')

str.splice(3, 1)
str = str.join('')

// str = 'Helo World'.
Alexandre Daubricourt answered 2020-01-10T20:58:00Z
3 votes
    var str = 'Hello World';
                str = setCharAt(str, 3, '');
                alert(str);

function setCharAt(str, index, chr)
        {
            if (index > str.length - 1) return str;
            return str.substr(0, index) + chr + str.substr(index + 1);
        }
Nikhil D answered 2020-01-10T20:58:15Z
1 votes

您可以使用substring()方法。 例如

var x = "Hello world"
var x = x.substring(0, i) + 'h' + x.substring(i+1);
Bhavesh Gangani answered 2020-01-10T20:58:35Z
0 votes
var str = 'Hello World',
    i = 3,
    result = str.substr(0, i-1)+str.substring(i);

alert(result);

i的值不应小于1

artis answered 2020-01-10T20:58:55Z
0 votes

嗨starbeamrainbowlabs,

您可以执行以下操作:

var oldValue = "pic quality, hello" ;
var newValue =  "hello";
var oldValueLength = oldValue.length ;
var newValueLength = newValue.length ;
var from = oldValue.search(newValue) ;
var to = from + newValueLength ;
var nes = oldValue.substr(0,from) + oldValue.substr(to,oldValueLength);
console.log(nes);

我在JavaScript控制台中对此进行了测试,因此您也可以查看谢谢

RamThakur answered 2020-01-10T20:59:24Z
translate from https://stackoverflow.com:/questions/11116501/remove-a-character-at-a-certain-position-in-a-string-javascript