我想寫一個正則表達式,使得接下來的事情就替換字符:取出並通過正則表達式
_
- 用空格>替換+
- >刪除它,如果沒有另一個+後(即c++
=>c++
c+
- >c
)'
- >中刪除它,如果它在該單詞的開始或結束(即Alin's
- >Alin's
。'Alin's
- >alin's
)&
,-
,.
,!
- 不要刪除。- 另一個特殊字符 - 刪除
我想這樣做,通過傳遞一個時間字符串
例如:
Input: "abc's, test_s! & c++ c+ 'Dirty's'. and beautiful'..."
Output: "abc's test s! & c++ c Dirty's. and beautiful..."
說明:
char `'` in `abc's,` stays because `3`
char `,` in `abc's,` was removed because `5`
char `_` in `test_s!` was replaced by space because `1`
char `!` in `test_s!` is not removed because `!`
char `&` is not removed because `4`
char `+` in `c++` is not removed because `2`
char `+` in `c+` was removed because `2`
word: `'Dirty's'.` was replaced to `Dirty's.` because `3` and `4`
char `'` in `beautiful'...` was removed because `3`
char `.` is not removed because of `4`
這是我的javascript
代碼:
var str = "abc's test_s c++ c+ 'Dirty's'. and beautiful";
console.log(str);
str = str.replace(/[_]/g, " ");
str = str.replace(/[^a-zA-Z0-9 &-.!]/g, "");
console.log(str);
這是我的jsfiddle:http://jsfiddle.net/alonshmiel/LKjYd/4/
我不喜歡我的代碼,因爲我敢肯定,它可能通過運行一次在字符串做。
任何幫助表示讚賞!
什麼是您給這個數據'「ABC的test_s輸出C++ c +'骯髒的'。和美麗的'' – 2015-02-07 14:10:57
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter – 2015-02-07 14:11:12
@AhosanKarimAsik,輸出是: 「Abc's test s C++ c Dirty's 。和美麗的「 – 2015-02-15 16:01:44