2016-01-21 144 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