我想写一个正则表达式,使得接下来的事情就替换字符:取出并通过正则表达式
_
- 用空格>替换+
- >删除它,如果没有另一个+后(即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