0

Hot to remove all number and all text from stringby using javascript replace javascript ?

https://jsfiddle.net/jgcsw41s/

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    var str = "123aBcD#$%"; 
    var res = str.replace("1-9,a-z,A-Z", "");
    alert(res);
}
</script>

When i tested my code it's not replace.

How can i do that ?

1
  • 1
    replace takes either a string or regular expression. You've provided a string, so you're trying to match the string literal "1-9,a-z,A-Z". Commented Jan 14, 2016 at 4:35

1 Answer 1

4

You might want to try, regex.

str.replace(/[a-zA-Z0-9]/g, '')

  1. [a-zA-Z0-9] match a single character present in the list below
  2. a-z a single character in the range between a and z (case sensitive)
  3. A-Z a single character in the range between A and Z (case sensitive)
  4. 0-9 a single character in the range between 0 and 9
  5. g modifier: global. All matches (don't return on first match)

Or as Rob mentioned (Thanks Rob).

str.replace(/\w/g, '')

will do too.

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

3 Comments

/\w/g seems a lot shorter. ;-)
Yes, but that will also replace underscores. So /[a-z\d]/i could work.
(?!_)\w can be used.

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.