2016-07-04 19 views
0

我知道:如何提取一個子字符串,並從JavaScript中的原始字符串中減去它?

> original_string = "bears and cats and dogs" 
'bears and cats and dogs' 
> useful_array = original_string.match(/cats/) 
[ 'cats', index: 10, input: 'bears and cats and dogs' ] 
> sub_string = useful_array[0] 
'cats' 

我將如何去獲得:

> modified_string 
'bears and and dogs' 

感謝

編輯:

> original_string = "bears and cats and dogs" 
'bears and cats and dogs' 
> original_string.replace(/cats/, "") 
'bears and and dogs' 

但有另一種方式?我來自紅寶石來所以總是一切

一個活潑的方法
+0

這回答在http://stackoverflow.com/questions/10398931/javascript-how-to-remove-text-from-a-string。 – RajeshM

回答

0

方法1:使用.replace()

var original_string = "bears and cats and dogs"; 
 

 
var modified_string = original_string.replace('cats ', ''); 
 

 
console.log(modified_string);

字符串有一個名爲replace方法,它接受各種參數,包括正則表達式,字符串,當然還有修飾符(g,i等)。

所以只要使用替換字符串來代替cats''將做你正在尋找。


方法2:使用一個數組,並過濾​​掉你不想

你的編輯的問題後,另一個更復雜的方式來做到這一點是將字符串分割成一個數組並過濾出單詞cats。然後通過空格將數組重新加入字符串中。

var original_string = "bears and cats and dogs"; 
 
var modified_string = original_string 
 
    .split(/\s/) 
 
    .filter(function(word) { 
 
    return (word !== 'cats') 
 
    }) 
 
    .join(' '); 
 

 
console.log(modified_string);


方法3:如果你想接近它的方式通過獲取子的指數,然後slice

當然,刪除它看起來像你,通過字符串索引,你可以這樣做:

var original_string = "bears and cats and dogs"; 
 
var wordToReplace = 'cats '; 
 

 
var index = original_string.indexOf(wordToReplace); 
 
var modified_string = ''; 
 

 
if (index > -1) { 
 
    modified_string = original_string.slice(0, index) + original_string.slice(index + wordToReplace.length); 
 
} 
 

 
console.log(modified_string);

+0

謝謝@KevBot,除了替換之外,還有其他的方式嗎? – mbigras

+0

@mbigras,我又增加了兩種方式。 – KevBot

相關問題