簡體   English   中英

如何使用jQuery將第一個單詞以外的文字包裹在span標簽中?

[英]How to wrap text in span tags except first word with jQuery?

是否可以將最后一個單詞包裝在帶有范圍標記的字符串中,但不包括第一個單詞? 因此,例如:

var string = 'My super text';

成為

My <span>super text</span>

我有這個:

var text = string.split(" ");

// drop the last word and store it in a variable
var last = text.pop();

// join the text back and if it has more than 1 word add the span tag
// to the last word
if (text.length > 0) {
   return text.join(" ") + " <span>" + last + "</span>";
}
else {
   return "<span>" + text.join(" ") + last + "</span>";
}

如果最后一個單詞至少有兩個,但是不確定如何修改,則用span標簽包裹最后一個單詞。

您只需要使用text.shift()返回第一個單詞,而不是text.pop()返回最后一個單詞。 然后,將更容易完成此操作。

var text= string.split(" ");

// get the first word and store it in a variable
var first = text.shift();

// join the text back and if it has more than 1 word add the span tag
// to the last word
if (text.length > 0) {
   return first + " <span>" + text.join(" ") + "</span>";
} else {
   return "<span>" + first + "</span>";
}

您可以使用正則表達式來實現。

text = text.replace(/\s(.*)$/, ' <span>$1</span>');

但是,您可能應該將以下內容轉換為遞歸函數...

$('body').contents().filter(function() {
    return this.nodeType == 3;
}).each(function() {
    var node = this;
    // Normalise node.
    node.data = $.trim(node.data);

    node.data.replace(/\s+(.*)\s*$/, function(all, match, offset) {
        var chunk = node.splitText(offset);
        chunk.parentNode.removeChild(chunk);
        var span = document.createElement('span');
        span.appendChild(document.createTextNode(' ' + match));
        node.parentNode.appendChild(span);
    });
});

jsFiddle

這將允許您修改文本節點並插入span元素,而不會弄亂序列化的HTML。

var space = string.indexOf(' ');

if (space !== -1) {
   return string.slice(0,space) + " <span>" + string.slice( space ) + "</span>";
} else {
   return "<span>" + string + "</span>";
}

您不必拆分文本,只需檢查是否有空格,然后在其中插入一個跨度即可。

這段代碼在第一個空格之后插入一個跨度,如果沒有空格(idx == -1),則將跨度放在字符串的開頭:

var idx = string.indexOf(' ');
return string.substr(0, idx + 1) + "<span>" + string.substr(idx + 1) + "</span>";

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM