简体   繁体   English

Javascript RegEx用下划线字符串替换单个下划线

[英]Javascript RegEx to replace single underscores with a string of underscores

I have a textarea where the user is able to type underscores. 我有一个textarea,用户可以在其中键入下划线。 I want to convert the underscores that they type to a string of 10 underscores. 我想将它们键入的下划线转换为10个下划线的字符串。 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, " _ ___ "); onkeyup:textarea.value.replace(/ _ * / g,“ _ ___ ”);

My thought being that it would match any string of underscores and automatically convert them to 10 underscores. 我的想法是,它将匹配任何下划线字符串,并自动将它们转换为10个下划线。

I get really odd behavior though. 我的行为确实很奇怪。 Typing an underscore results in 20 underscores. 键入下划线会产生20个下划线。 Also, it seems to be matching the left and right of any character I type. 另外,它似乎与我键入的任何字符的左右匹配。 For example, if I type "A", I get: 例如,如果键入“ A”,则会得到:

___ A _ __ ___ 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. *表达式中的字符匹配零个或多个字符,因此它与下划线后的空字符串匹配,并用10个下划线替换。 + matches one-or-more. +匹配一个或多个。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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