我有這樣一個標題:jQuery的 - 找到字符串中的字符和包裹其餘的字符
foobar|foo
如何搜索字符「|」,然後把它包在跨度其餘的字符一起在右邊?
結果應該是:
foobar< span>|foo< /span>.
在網站上,我們有不同長度的標題,如:
hello|my mario
you are the best|my friend
所以我想檢測 '|'字符並用剩下的包裝起來。
我有這樣一個標題:jQuery的 - 找到字符串中的字符和包裹其餘的字符
foobar|foo
如何搜索字符「|」,然後把它包在跨度其餘的字符一起在右邊?
結果應該是:
foobar< span>|foo< /span>.
在網站上,我們有不同長度的標題,如:
hello|my mario
you are the best|my friend
所以我想檢測 '|'字符並用剩下的包裝起來。
通過@guedes啓發回答
試試這個:
var headingText = $('h2').text();
var newText = (headingText.replace(/\|[^]*$/, ' <span>$&</span>'));
$('h2.heading').html(newText)
html
<h2 class="heading">foobar|foo</h2>
你可以有任何你喜歡的標題.eg
bar | foo
doodle | lorem。
正是我所需要的,謝謝。 – delled
古埃德斯答案肯定是更少的代碼 - 而另一種方式可以是:
var val = 'foobar|foo';
var before = val.substr(0, val.indexOf('|'));
var after = val.substr(val.indexOf("|") + 1);
$('.result').empty().append(before +'<span>|' + after + '</span>');
這裏是您可以使用測試小提琴:Fiddle link
分享你的研究可以幫助每個人。告訴我們你試過的東西以及爲什麼 它不符合你的需求。這表明你已經花時間 試圖幫助自己,它使我們避免重申明顯的答案, ,最重要的是它可以幫助您獲得更具體和相關的答案! 另請參閱[問]。 – RamenChef
'console.log('foobar | foo'.replace(/ \ | [^] * $ /,' $&'));' –
thanks @Guedes ..這是有用的。 – delled