我有一行文本是帖子标题,它看起来像这样:
<h2 class="title">
<a href="http://example.com">Report 10/2019 The name of the report</a>
</h2>
我希望能够:
a) 在年份后拆分链接标题的名称;
b) 以两种不同的方式分别为“Report 10/2019”和名称的其余部分设置样式(最好为每个部分或至少为第一部分添加一个类)。
我设法用这个分割文本:
var breakAt = 17;
var brokenString = $(".title a").html();
brokenString = brokenString.substring(0, breakAt) + "<br>" + brokenString.substring(breakAt);
$(".title a").html(brokenString);
但这会将名称除以字符数,而在 X 个空格后拆分(在本例中是在第二个空格后)会更安全 - 月数将是一个或两个字符。 并且不知道如何对标题链接的两个部分应用不同的样式。
最佳答案
循环遍历所有标题,获取它们的内容,应用正则表达式并将子字符串从开头到年份(4 位数字)包装到 span
(或其他元素,如果您愿意)
然后将样式应用到 span
(例如更粗的字体和 display: block
),以便剩余部分在新行开始)
var titles = document.querySelectorAll('.title a');
[...titles].forEach((title) => {
var content = title.textContent;
content = content.replace(/(^.+?\d{4})/, '<span>$1</span>');
title.innerHTML = content;
})
.title a {
color: #333;
font-weight: 400;
}
.title span {
font-weight: 700;
display: block;
}
<h2 class="title">
<a href="http://example.com">Report 10/2019 The name of the report</a>
</h2>
<h2 class="title">
<a href="http://example.com">Another Report 3 / 2019 The name of the report</a>
</h2>
关于javascript - n字+样式后单行文字如何拆分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57161067/