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.

3
  • Sometimes you cannot be both short and elegant while being quick at the same time. Commented Jul 21, 2016 at 19:03
  • View this entry from 2008: "RegEx for JavaScript to allow only alphanumeric". Commented Jul 21, 2016 at 19:06
  • @SpencerWieczorek but in this case you can Commented Jul 21, 2016 at 22:03

3 Answers 3

18

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);

Sign up to request clarification or add additional context in comments.

2 Comments

\d is probably better than 0-9
The "i" is what i missed in my attempts!
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()

Comments

-1
var NewString = (OldString).replace(/([^0-9a-z])/ig, "");

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.