如何按位置号从字符串中删除字符

How to remove character from string by position number?

本文关键字:删除 字符 字符串 何按 位置      更新时间:2023-09-26

我有一个这样的字符串:

var str = "this is a **test";

现在我想删除那两颗星(位置1011)。我想要这个:

var newstar = "this is a test";

同样,我想使用它们的位置编号删除它们。我该怎么做?

您也可以使用string.replace

> var str = "this is a **test";
> str.replace(/^(.{10})../, '$1')
'this is a test'

^(.{10})捕获前 10 个字符,接下来的..与第 11 个字符和第 12 个字符匹配。因此,通过用捕获的字符替换所有匹配的字符将为您提供预期的输出。

如果你想满足位置条件加上字符编码,那么你的正则表达式必须是,

str.replace(/^(.{10})'*'*/, '$1')
只有当它

被放置在位置11和12时,它才会取代两颗星。

您也可以使用构造函数在正则表达式中使用变量RegExp变量。

var str = "this is a ***test";
var pos = 10
var num = 3
alert(str.replace(new RegExp("^(.{" + pos + "}).{" + num + "}"), '$1'))

你可以使用 .slice 两次

var str = "this is a **test";
str =  str.slice(0, 10)+ str.slice(11);
str=str.slice(0, 10)+str.slice(11);
'this is a test'
您可以使用

var str = "this is a **test";
var ref = str.replace(/'*/g, '');     //it will remove all occurrences of *
console.log(ref)   //this is a test