javascript replace line breaks AND special characters

爱⌒轻易说出口 提交于 2019-12-11 12:04:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!