简体   繁体   中英

javascript replace line breaks AND special characters

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,'_'));

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,'')

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM