带有jquery的字符串中的第一个单词

时间:2010-09-21 12:05:37

标签: jquery string

我正在尝试找出能够帮助我将字符串中的第一个单词换成span的函数。

但遗憾的是没有运气。

有人可以帮我吗?

非常感谢

的Dom

4 个答案:

答案 0 :(得分:22)

一种方式:

$('something').each(function(){
     var me = $(this);
     me.html(me.html().replace(/^(\w+)/, '<span>$1</span>'));
});

[source | try it]

基本上,对于每个匹配(something),您将第一个单词替换为$1标记中包含的自身(<span>)。字符类\w匹配字母,数字和下划线(因此定义“单词”是什么 - 您可能需要另一个定义)。

答案 1 :(得分:4)

您在jQuery询问如何做到这一点。我认为你需要一个正则表达式添加范围

这是一个使用jQuery从DOM获取文本并在使用正则表达式将span添加到字符串后在DOM中进行更新的示例。

<div id="container">This is the text</div>
<script type="text/javascript">
jQuery(function($){
    // get the text you want to transform in a variable
    var html = $('#container').html();
    // doing the transformation (adding the span) with a regular expression
    html = html.replace(/^([^\s]*)(.*)/, "<span class=\"first-word\">$1</span>$2");
    // update your text
    $('#container').html(html);

    // or in one line:
    $('#container').html( ('#container').html().replace(/^([^\s]*)(.*)/, "<span class=\"first-word\">$1</span>$2") );
});
</script>

这是你得到的:

<div id="container"><span class="first-word">This</span> is the text</div>

答案 2 :(得分:-1)

-D

答案 3 :(得分:-1)

var first;
var i=0;
$("p").each(function() {
first = $("p")[i].innerHTML;
$("p")[i].innerHTML = "<span class='first'>" + first.slice(0, first.indexOf(' ')) + "</span>" + first.slice(first.indexOf(' '));
i++;
});