简体   繁体   中英

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.

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.

将您的模式更改为/ _ {1,} /,这将匹配_或_ ,您之前的模式将匹配_ ,之后匹配任意数量的字符。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM