Anthony Velardo
Anthony Velardo

Reputation: 21

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.

Upvotes: 0

Views: 2035

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174706

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.

Upvotes: 5

Related Questions