jquery - 使用 css/js 将第二个单词修剪为其第一个字母

标签 jquery html css

我有以下 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/

相关文章:

jquery - 如何去除隐藏div占用的空间

jquery - 如何使用 jQuery 为属性值(不是样式属性)设置动画?

html - 悬停时延迟图像显示

html - 除非用户清除缓存,否则不会在网站上显示新内容

javascript - 为什么我用 jQuery 添加的新段落在单击时没有任何反应?

javascript - 表格自动 TR 计数

css - 媒体查询 : background-image not displayed

jQuery 验证不验证

plugins - jQuery 延迟加载是否有任何真正的性能提升?

jquery - 如何将 Prototype 和 jQuery 与 Scriptaculous 集成?