Replace letters in a string with an underscore in javascript

How do you replace every letter in a string with an underscore in javascript.

For example I would like the string of "name" to be replaced with _ _ _ _.

Is there a way I can specify letters a-z and replace it with an underscore.

Thanks in advance.

Answers 1

  • Simple,

    str.replace(/[a-z]/g, '_')

    to replace both upper and lowercase letters,

    str.replace(/[a-z]/gi, '_')
    • [a-z] matches any lowercase letter.
    • g global modifier helps to do the match globally.
    • i case-insensitive modifier helps to do a case insensitive match.

Related Articles