xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

js regexp remove all non-alphanumeric characters All In One

js regexp remove all non-alphanumeric characters All In One

alphanumeric characters / word character

const str = '123abc x . / m';
// 正向处理 \W
const pureStr = str.replace(/[\W_]+/g, '');
// '123abcxm'
const str = '123abc x . / m';
// 反向处理 ^
const pureStr = str.replace(/[^0-9A-Za-z]/g, ``).toLowerCase();
// '123abcxm'

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Character_Classes#types

\W

Matches any character that is not a word character from the basic Latin alphabet.
Equivalent to [^A-Za-z0-9_].

For example, /\W/ or /[^A-Za-z0-9_]/ matches "%" in "50%" and "É" in "Émanuel".

匹配任何不是来自基本拉丁字母的单词字符的字符。
等价于 [^A-Za-z0-9_]

demo

const p = `
	The quick brown fox jumps over the lazy dog. 
    If the dog reacted, was it really lazy?
`;

console.log(p.replaceAll('dog', '👻'));


// global flag required when calling replaceAll with regex
const regex = /Dog/ig;
console.log(p.replaceAll(regex, '💩'));

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll

refs

https://stackoverflow.com/questions/20864893/replace-all-non-alphanumeric-characters-new-lines-and-multiple-white-space-wit

https://bobbyhadz.com/blog/javascript-remove-non-alphanumeric-characters-from-string



©xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2022-03-09 23:09  xgqfrms  阅读(29)  评论(2编辑  收藏  举报