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

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

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

我所期待的结果是:

"Helo World"

这个问题不是 如何使用 JavaScript 从字符串中删除字符?的副本,因为这个问题是关于移除特定位置的字符,这个问题是关于移除字符的所有实例。

184604 次浏览

It depends how easy you find the following, which uses simple String methods (in this case slice()).

var str = "Hello World";
str = str.slice(0, 3) + str.slice(4);
console.log(str)

    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);
}

You can try it this way:

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

Here is a live example: http://jsbin.com/ogagaq

var str = 'Hello World',
i = 3,
result = str.substr(0, i-1)+str.substring(i);


alert(result);

Value of i should not be less then 1.

you can use substring() method. ex,

var x = "Hello world"
var x = x.substring(0, i) + 'h' + x.substring(i+1);

Hi starbeamrainbowlabs ,

You can do this with the following:

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);

I tested this in my javascript console so you can also check this out Thanks

Turn the string into array, cut a character at specified index and turn back to string

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


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


// str = 'Helo World'.

If you omit the particular index character then use this method

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

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


// Output: "Helo world"