最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Quick way to extract alphanumeric characters from a string in Javascript - Stack Overflow

programmeradmin1浏览0评论

I know that I can write a simple loop to check each character in a string and see if it is a alphanumeric character. If it is one, concat it to a new string. And thats it.

But, is there a more elegant shortcut to do so. I have a string (with CSS selectors to be precise) and I need to extract only alphanumeric characters from that string.

I know that I can write a simple loop to check each character in a string and see if it is a alphanumeric character. If it is one, concat it to a new string. And thats it.

But, is there a more elegant shortcut to do so. I have a string (with CSS selectors to be precise) and I need to extract only alphanumeric characters from that string.

Share Improve this question asked Jul 21, 2016 at 19:00 SunnySunny 10.1k12 gold badges55 silver badges90 bronze badges 3
  • Sometimes you cannot be both short and elegant while being quick at the same time. – Spencer Wieczorek Commented Jul 21, 2016 at 19:03
  • View this entry from 2008: "RegEx for JavaScript to allow only alphanumeric". – JohnH Commented Jul 21, 2016 at 19:06
  • @SpencerWieczorek but in this case you can – Patrick Roberts Commented Jul 21, 2016 at 22:03
Add a comment  | 

3 Answers 3

Reset to default 17

Many ways to do it, basic regular expression with replace

var str = "123^&*^&*^asdasdsad";
var clean = str.replace(/[^0-9A-Z]+/gi,"");
console.log(str);
console.log(clean);

"sdfasfasdf1 yx6fg4 { df6gjn0 } yx".match(/([0-9a-zA-Z ])/g).join("")

where sdfasfasdf1 yx6fg4 { df6gjn0 } yx can be replaced by string variable. For example

var input = "hello { font-size: 14px }";
console.log(input.match(/([0-9a-zA-Z ])/g).join(""))

You can also create a custom method on string for that. Include into your project on start this

String.prototype.alphanumeric = function () {
    return this.match(/([0-9a-zA-Z ])/g).join("");
}

then you can everythink in your project call just

var input = "hello { font-size: 14px }";
console.log(input.alphanumeric());

or directly

"sdfasfasdf1 yx6fg4 { df6gjn0 } yx".alphanumeric()
var NewString = (OldString).replace(/([^0-9a-z])/ig, "");

where OldString is the string you want to remove the non-alphanumeric characters from

发布评论

评论列表(0)

  1. 暂无评论