问题
I added a ".replace" to my alert to remove/replace line breaks and hard returns and it works great.
alert((foo + bar).replace(/(\n|\r)/g,''));
I want to add a similar piece to replace special characters. This works on it's own, but how do I combine the two so it removes breaks AND spec characters?
.replace(/[^a-zA-Z0-9]/g,'_');
This was my best guess at it and it's not working....
alert((foo + bar).replace(/(\n|\r)/g,''),(/[^a-zA-Z0-9]/g,'_'));
回答1:
If you want to replace with different strings like you showed in your example
alert((foo + bar).replace(/(\n|\r)/g,'').replace(/[^a-zA-Z0-9]/g,'_'));
If both can be replaced with an empty string
alert((foo + bar).replace(/(\n|\r|[^a-zA-Z0-9])/g,'')
回答2:
Version # 1
You can add a new method to the String prototype property
String.prototype.stripSpecialChars = function() {
return this.replace(/(\n|\r|[^a-zA-Z0-9])/g,'');
}
and use
(foo + bar).stripSpecialChars();
Version # 2
You can also just write a function that does the same thing
function stripSpecialChars(text) {
return text.replace(/(\n|\r|[^a-zA-Z0-9])/g,'');
}
and use
stripSpecialChars(foo + bar)
来源:https://stackoverflow.com/questions/29520897/javascript-replace-line-breaks-and-special-characters