5

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
  • 9,245
  • 10
  • 49
  • 79

3 Answers3

16

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
  • 49,224
  • 10
  • 102
  • 153
epascarello
  • 204,599
  • 20
  • 195
  • 236
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,694
  • 2
  • 26
  • 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
  • 2,425
  • 2
  • 26
  • 43