2013-03-15 48 views
2

我有三個字,我想第一個空間後,周圍添加內容的跨度,以便jQuery的間隔後,第一空間

hello world成爲hello <span>world</span>

hello world again成爲hello <span>world again</span>

任何幫助將不勝感激

在這裏編輯它是

$("#main-nav li a").each(function(index) { 
    $(this).html($(this).text().replace(/([\S]*)\s(.*)/, "$1 <span>$2</span>")); 
}); 
+0

從這些詞來自哪裏?你能告訴我們更好的理解代碼嗎? – Raman 2013-03-15 07:51:20

回答

5

你可以用一些正則表達式做到這一點:

text = text.replace(/([\S]*)\s(.*)/, "$1 <span>$2</span>"); 

如果texthello world,上面的代碼將其轉換爲hello <span>world</span>

+0

如果文字長於兩個單詞,則效果不佳。 – sQVe 2013-03-15 07:56:49

+0

@sQVe - 你說得對。沒有注意到!嗯..它只匹配最後一個'\ s'! – techfoobar 2013-03-15 07:58:50

+0

改用'(。\ s)+(。*)'。 – sQVe 2013-03-15 07:59:43

1

也許更容易理解(我肯定),

  1. 對空格字符使用find方法,得到字符串中的第一個位置。
  2. 獲取從索引0到特定位置的第一個子串。
  3. 從特定位置獲取子串到string.length並將它們包裝
  4. 將兩個字符串合併一次。