2011-12-09 22 views
1

是否有可能用字符串標記排除第一個字的字符串中的最後一個字?所以這將會是例如:如何在span標籤中包裝除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標籤包裝的最後一個字,如果它有至少兩個但不確定如何修改它。

在此先感謝!

回答

2

您只需要使用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>"; 
} 
+0

真棒的感謝! – javiervd

1
var space = string.indexOf(' '); 

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

你可以用正則表達式做。

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。

1

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

此代碼插入一個跨度第一空間後,如果沒有空間(IDX == -1),跨度放在字符串的開頭:

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