2016-01-21 143 views
0

我有一个字符串是这样的:如何通过位置号从字符串中删除字符?

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

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

var newstar = "this is a test"; 

再次,我想删除他们使用他们的位置数量。我怎样才能做到这一点?

+2

后乌尔尝试? –

+0

@AvinashRaj这是我猜测的结果:'str.slice(' – stack

回答

6

您也可以使用string.replace

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

^(.{10})捕获前10个字符和以下..第11和第12字符匹配。所以通过用捕获的字符替换所有匹配的字符将会给你预期的输出。

如果要满足那么你的正则表达式必须是区位条件,加上性格codition,

str.replace(/^(.{10})\*\*/, '$1') 

这将取代两颗星,只有当它被放置在POS 11和12

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

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

+0

)使用'..'对我来说真的很有趣..我喜欢+1,但实际上这些角色不一样..请你也告诉我我怎么能不用'..'? – stack

+1

@stack'.'匹配除换行符之外的任何字符,如果你想匹配换行符,则使用'[\ s \ S]'而不是'.' –

+0

用这个例子检查一下'var str =“这是一个?ktest”;' –

0

您可以使用.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' 
0

您可以使用

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

var ref = str.replace(/\*/g, '');  //it will remove all occurrences of * 

console.log(ref) //this is a test