[英]Javascript - Replacing any instance of character in a string
Take the following string: 请使用以下字符串:
Lodder
What I'm trying to do is, ensure the above is the result of any alternatives that are written on keypress
. 我要做的是,确保以上是在keypress
上写的任何替代品的结果。 Possible alternatives could be something like: 可能的替代方案可能是这样的:
Lo a der Lo a der
Lo [a] der Lo [a] der
Lo .a der Lo .a der
The alternatives are always based on the letter a
replacing the first d
in the string 替代方案总是基于字母a
替换字符串中的第一个d
The code I've written so far: 我到目前为止编写的代码:
$('#element').keyup(function(e) {
var Lodder = this.value.replace(/Loader|Lo4der/g, 'Lodder');
if (Lodder != this.value)
{
this.value = Lodder;
}
});
As you can see, it only replaces exact alternatives, however I'm trying to make it more dynamic by detecting more advanced alternatives. 正如您所看到的,它只取代了确切的替代方案,但是我试图通过检测更高级的替代方案来使其更具动态性。
Is there a more or less simple, but, robust solution to this? 是否有一个或多或少简单但强大的解决方案?
If so, could someone point me in the right direction? 如果是这样,有人会指出我正确的方向吗?
Use .*?
使用.*?
to match any number of characters non-greedily. 非贪婪地匹配任意数量的字符。
value.replace(/\bLo.*?der\b/g, 'Lodder');
\\b
called word boundary which matches between a word character and a non-word character ( vice-versa ). \\b
称为单词边界,它在单词字符和非单词字符之间匹配( 反之亦然 )。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.