2013-03-22 24 views
1

我有以下格式的字符串。我試圖在Java腳本中創建一個函數來刪除某些字符。使用Javascript從字符串中刪除字符

樣品字符串:

Var s = '18160 ~ SCC-Hard Drive ~ 4 ~ d | 18170 ~ SCC-SSD ~ 4 ~ de | 18180 ~ SCC-Monitor ~ 5 ~ | 18190 ~ SCC-Keyboard ~ null ~' 

所需的結果:

s = 'SCC-Hard Drive ~ 4 ~ d | SCC-SSD ~ 4 ~ de | SCC-Monitor ~ 5 ~ |SCC-Keyboard ~ null ~' 

如果您發現該ID的上述例如18160,18170,18180和18190被拆除。這只是一個例子。結構如下:

id: 18160 
description : SCC-Hard Drive 
Type: 4 
comment: d 

那麼,有多個項目,他們使用派克定界符得到級聯。所以我的要求是從上述結構中給定的字符串中刪除id。

+0

有什麼要求?這個字符串會改變嗎?數字總是一樣嗎?即。 18 ***? – brbcoding 2013-03-22 17:23:55

+0

什麼定義了需要刪除的部分? – 2013-03-22 17:24:01

+0

如果它們都是相同的格式,我建議通過正則表達式運行它 – gehsekky 2013-03-22 17:24:03

回答

3

也許使用string.replace()方法。

s.replace(/\d{5}\s~\s/g, "") 

\d{5} - matches 5 digits (the id) 
\s - matches a single space character 
~  - matches the ~ literally 

輸出:

"SCC-Hard Drive ~ 4 ~ d | SCC-SSD ~ 4 ~ de | SCC-Monitor ~ 5 ~ | SCC-Keyboard ~ null ~" 

另外,請注意Var無效。它應該是var

1

由於ID字段中的位數可能會有所不同,因此我將使用替換函數和以下正則表達式。

s.replace(/(^|\|\s)\d+\s~\s/g, '$1')