2013-12-16 36 views
0

我使用JavaScript獲取div的html值。它返回像如何使用JavaScript在特定單詞之前切分文本

From looking down the Line, he turned himself about again, and, raising his eyes, saw my figure high above him.Without prolonging the narrative to dwell on any one of its curious circumstances more than on any other, I may, in closing it, point out the coincidence that the warning of the Engine-Driver included, not only the words which the unfortunate Signal-man had repeated to me as haunting him, but also the words which I myself—not he—had attached, and that only in my own mind, to the gesticulation he had imitated. 

我需要之前和特定text.unfortunate後切片值是特定的詞的價值。例如,我需要得到像下面

....引擎驅動程序包括,不僅不幸的話信號人重複了我,作爲困擾他,但也是我自己的話。 ...

+2

你爲什麼要做那 –

+0

@ArunPJohny我正在搜索div中的單詞。 ir返回全部內容。我需要在該單詞的前後切片 – Jegadeesan

+0

我的問題是切片後想要做什麼...你想突出顯示它 –

回答

0

基於更新的評論,您需要突出的話,所以你可以用一個簡單的正則表達式使用.replace()之類

$('div').html(function(_, html){ 
    return html.replace(/(unfortunate)/gi, '<b>$1</b>') 
}) 

演示:Fiddle

0

您可以使用indexOf()substring()的組合。使用indexOf(「unfornate」)查找不幸的詞的索引,然後使用該索引找到子字符串。

0

如果你想分裂字符串考慮逗號(,)作爲分隔符,那麼你應該做的像,

var yourString='From looking down the Line, he turned himself about again, and, raising his eyes, saw my figure high above him.Without prolonging the narrative to dwell on any one of its curious circumstances more than on any other, I may, in closing it, point out the coincidence that the warning of the Engine-Driver included, not only the words which the unfortunate Signal-man had repeated to me as haunting him, but also the words which I myself—not he—had attached, and that only in my own mind, to the gesticulation he had imitated.'; 

var arrResult=yourString.split(','); //this will return an array 

DEMO

+0

@Jegadeesan,在閱讀您的評論之後,如果您想將字符串切片爲「不幸」的話,我建議您應該使用yourString.split('不幸')。 – anand4tech

1

假設你的文本是divtxt然後使用這個

var splitText=divtxt.split("unfortunate"); 

splitText [0]在「不幸」之前將具有文本,而splitText [1]將在「不幸」之後具有文本「

0

如果你想 - 」......引擎驅動程序包括在內,不僅是那些不幸的信號人重複給我的話讓他困擾,還有我自己的話......「

var str = "From looking down the Line, he turned himself about again, and, raising his eyes, saw my figure high above him.Without prolonging the narrative to dwell on any one of its curious circumstances more than on any other, I may, in closing it, point out the coincidence that the warning of the Engine-Driver included, not only the words which the unfortunate Signal-man had repeated to me as haunting him, but also the words which I myself—not he—had attached, and that only in my own mind, to the gesticulation he had imitated." 
    var i = str.indexOf('unfortunate'); 
    var j = str.indexOf('Engine'); 
    var k = str.indexOf('myself') 
    var result = "..." + str.substring(j,i) + str.substring(i,k) + "..."; 
相關問題