= 20) 而不是 slice(0, 20) 这样就-6ren">
gpt4 book ai didi

javascript - Jquery使用 "count"而不是 "slice"

转载 作者:行者123 更新时间:2023-11-28 18:56:26 25 4
gpt4 key购买 nike

我的代码应该在 x 个单词后放置一个横幅。该代码可以工作,但没有达到应有的效果,因为它使用 slice 进行计数或切片。我需要使用 (count >= 20) 而不是 slice(0, 20)

这样就会计算文本中的单词数,而不是计算行数。这是执行我需要的代码:https://jsfiddle.net/714Lmgfu/3/但是,此代码中有一个循环,它复制了图像(如 fiddle 中所示),并且我无法使 return false 工作。

所以我得到了一些帮助,这就是最终结果 https://jsfiddle.net/scadp0ar/ ,此代码按其应有的方式工作,除了如前所述,它不计算单词数。我应该改变什么才能让它计算单词数?

例如,更改:

  var img = '<img src="http://blog.leadlovers.com.br/wp-content/uploads/sites/23/2014/03/marca21-160x160.png" />'

$(".newsitem_text").html(function (i, h) {
return h.replace(h.split(/\s+/).slice(0, 20).join(' '), function (m) {
return m + img; });
});

对于:

function check() {
if (count >= 20) {
newHtml += '<img src="http://blog.leadlovers.com.br/wp-content/uploads/sites/23/2014/03/marca21-160x160.png" />'
count = 0;
}
}

最佳答案

var img = '<img src="http://blog.leadlovers.com.br/wp-content/uploads/sites/23/2014/03/marca21-160x160.png" />'

$(".newsitem_text").html(function (i, h) {
// Match a word followed by one or more spaces 20 times
// Insert <img>-tag
// Repeat
return h.replace(/([^\s]+\s+){20}/g, function (m) {
return m + img;
});
});

分割:

/ # Start regex
( # Start capturing group
[^\s]+ # Match everything - but space - 1 or more times
# could also be written as .+? that means:
# match everything 1 or more times, but not gready (meaning that if a space is encountered it will stop matching)
\s+ # Match space 1 or more times
) # End group
{20} # repeat 20 times
/ # End regex
g # global flag - will run the regex multiply times until no more matches are posible

关于javascript - Jquery使用 "count"而不是 "slice",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33556235/

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