user1464652
user1464652

Reputation: 55

Javascript RegEx to replace single underscores with a string of underscores

I have a textarea where the user is able to type underscores. I want to convert the underscores that they type to a string of 10 underscores. I want this to be done in real time as they type.

_ => ____

I had thought that I could do something as simple as:

onkeyup: textarea.value.replace(/_*/g, "____");

My thought being that it would match any string of underscores and automatically convert them to 10 underscores.

I get really odd behavior though. Typing an underscore results in 20 underscores. Also, it seems to be matching the left and right of any character I type. For example, if I type "A", I get:

___A___

Does anybody know how to get this working properly? Seems so simple yet I am stumped. Thanks.

Upvotes: 0

Views: 100

Answers (2)

Barmar
Barmar

Reputation: 781058

Use /_+/ rather than /_*/. * in a regexp matches zero-or-more of the character, so it's matching the empty string after the underscore and replacing it with 10 underscores. + matches one-or-more.

Upvotes: 1

alexmac
alexmac

Reputation: 239

change your pattern to /_{1,}/ this will match _ or _ , your prior pattern matched _ and any number of characters afterwards.

Upvotes: 0

Related Questions