簡體   English   中英

如何使用JavaScript在特定單詞之后切出文本

[英]how to slice the text before after a particular word using JavaScript

我正在使用JavaScript獲取div的html值。 它返回像

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.

我需要在特定文本之前和之后對值進行切片。不幸的是該特定單詞。 例如,我需要像下面這樣

.... Engine-Driver不僅包括不幸的信號員在困擾他時向我重復的單詞,還包括我自己的單詞。

假設您的文本在divtxt中,則使用此

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

splitText [0]在“不幸”之前有文字,splitText [1]在“不幸”之后有文字

您可以結合使用indexOf()substring() 使用indexOf(“ unfornate”)查找不幸單詞的索引,然后使用該索引為子字符串。

如果您嘗試使用逗號(,)作為分隔符來拆分字符串,則應這樣做,

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

演示

如果您想要-“ ....引擎驅動程序,不僅包括不幸的信號員在困擾他時向我重復的單詞,還包括我自己的單詞...”

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) + "...";

根據更新的注釋,您需要突出顯示單詞,以便可以將.replace()與簡單的正則表達式一起使用,例如

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

演示: 小提琴

暫無
暫無

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

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