gpt4 book ai didi

javascript - 当在 TextArea 中键入超链接时,减少 javascript 中的计数器

转载 作者:行者123 更新时间:2023-12-03 01:37:55 25 4
gpt4 key购买 nike

我有一个文本区域,将在其中键入文本,并且当键入文本时,对于键入的每个字符,计数器将减少 1..但我希望当在文本区域中键入登陆链接时,计数器将减少正好 16,之后再次输入普通文本时,每个字符将减 1....任何形式的帮助将不胜感激,谢谢

文本区域

var maxLimit = 160;
$(document).ready(function(e) {
$('#msgArea').keyup(function() {
var lengthCount = this.value.length;
if (lengthCount > maxLimit) {
this.value = this.value.substring(0, maxLimit);
var charactersLeft = maxLimit - lengthCount + 1;
$('#msgArea').css('background-color', '#FFFF00');
} else {
var charactersLeft;
var textmsg = document.getElementById('msgArea').value;
var pattern = new RegExp(
'((http|https)(://))?([a-zA-Z0-9]+[.]{1}){2}[a-zA-z0-9]+(/{1}[a-zA-Z0-9]+)*/?',
'i'
);
if (pattern.test(textmsg)) {
lengthCount = lengthCount - 16;
charactersLeft = maxLimit - lengthCount;
} else {
charactersLeft = maxLimit - lengthCount;
$('#spnCharLeft').text(charactersLeft + ' Characters left');
}
}
$('#spnCharLeft').css('display', 'block');
if (lengthCount < maxLimit) {
$('#msgArea').css('background-color', '#fff');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-offset-2 col-sm-10">
<label>Message</label>
<textarea id="msgArea" class="form-control" rows="3"></textarea>
<span id="spnCharLeft"></span>
</div>

最佳答案

var maxLimit = 160;
$(document).ready(function(e) {
$('#msgArea').keyup(function() {
var spanCharLeft = $('#spnCharLeft');
var charactersLeft;
var textmsg = this.value;
var lengthCount = textmsg.length;
var pattern = new RegExp(
'((http|https)(://))?([a-zA-Z0-9]+[.]{1}){2}[a-zA-z0-9]+(/{1}[a-zA-Z0-9]+)*/?',
'ig'
);
var matches = textmsg.match(pattern);
if (!matches) {
matches = [];
}
matches.forEach(matched_string => {
lengthCount = lengthCount - matched_string.length + 16;
});

charactersLeft = maxLimit - lengthCount;
spanCharLeft.text(charactersLeft + ' Characters left');
if (lengthCount < maxLimit) {
$('#msgArea').css('background-color', '#fff');
} else {
this.value = this.value.substring(0, maxLimit);
spanCharLeft.text('0' + ' Characters left');
$('#msgArea').css('background-color', '#fff000');
}

$('#msgArea').css('display', 'block');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-offset-2 col-sm-10">
<label>Message</label>
<textarea id="msgArea" class="form-control" rows="3"></textarea>
<span id="spnCharLeft"></span>
</div>

这应该可以做到。记下 matches = textmsg.match(pattern) 的使用。您需要解析模式的每个匹配项的字符串,然后适当增加 lengthCount lengthCount = lengthCount -matched_string.length + 16。另请注意,我已更改正则表达式以使用 g 全局标志。

PS:我意识到这部分很丑

if(!matches) {
matches = [];
}

我希望对此进行编辑

关于javascript - 当在 TextArea 中键入超链接时,减少 javascript 中的计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50986116/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com