gpt4 book ai didi

javascript - 将字符串的前几个单词换行

转载 作者:行者123 更新时间:2023-12-03 02:10:02 32 4
gpt4 key购买 nike

我有一个字符串,我需要将这个字符串的前几个单词换行,这些前几个单词的数量总是不同的。我可以获取前几个单词的子字符串,但无法将其包装在 span 中。如何将每个字符串中的每个子字符串包裹起来?

$('.title-js').each(function(){
var titleText = $(this).text().trim();
var $wordLength = parseInt($.trim($(this).text()).split(' ').length);
var half = $wordLength/2;
var halfString = titleText.split(' ').slice(0,half).join(' ');

$(halfString).wrap("<span class = 'golden-words'></span>"); //here is a problem

$(this).html(function(_,txt) {
return txt.replace(/(.$)/, "<span class = 'golden-words'>$1</span>");
});

});
.golden-words {
color: gold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class = "title title-js">Some text part first.</div>
<div class = "title title-js">Some text part second!</div>
<div class = "title title-js">Some text part third?</div>
<div class = "title title-js">Some text part fourth)</div>

最佳答案

您从未将元素的内容分配给halfString,也未将其与另一半内容组合。 txt.replace正则表达式仅匹配一个字符 (.) 和字符串末尾 ($)。

这应该有效:

$('.title-js').each(function(){
var parts = $.trim($(this).text()).split(' ');

var half = parts.length / 2;
var firstHalf = parts.slice(0,half).join(' ');
var secondHalf = parts.slice(half).join(' ');

$(this).html("<span class = 'golden-words'>"+firstHalf+"</span> " + secondHalf);


});
.golden-words {
color: gold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class = "title title-js">Some text part first.</div>
<div class = "title title-js">Some text part second!</div>
<div class = "title title-js">Some text part third?</div>
<div class = "title title-js">Some text part fourth)</div>

关于javascript - 将字符串的前几个单词换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49617599/

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