3

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.

Sunny
  • 7,989
  • 7
  • 40
  • 73

3 Answers3

13

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);
Patrick Roberts
  • 44,815
  • 8
  • 87
  • 134
epascarello
  • 195,511
  • 20
  • 184
  • 225
1
"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()
Misaz
  • 3,268
  • 1
  • 29
  • 42
-1
var NewString = (OldString).replace(/([^0-9a-z])/ig, "");

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

user3163495
  • 1,364
  • 2
  • 15
  • 35