我有以下 div。其中的文本将是动态的。
<div class="full_name">Libin Babu</div>
我想要的结果是 Libin B.
那是我想将第二个名字修剪成它的第一个字母,然后是一个“点”。 对 CSS 或 jQuery 有帮助吗?我更喜欢 css 解决方案。
谢谢。
最佳答案
您可以使用替换/正则表达式:
"Libin Babu".replace(/^(\S+)\s+(\S).*/, '$1 $2.')
// "Libin B."
要将其替换到位,您可以使用:
$('.full_name').each(function (d, div) {
$(div).text($(div).text().replace(/^(\S+)\s+(\S).*/, '$1 $2.'));
});
正则解释:
/ // Regex start
^ // Beggining of the string
(\S+) // One or more non-whitespace characters in group $1
\s+ // One or more whitespace characters
(\S) // Exactly one non-whitespace character in group $2
.* // Any number of any characters
/ // Regex end
关于jquery - 使用 css/js 将第二个单词修剪为其第一个字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19584898/