我使用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.
我需要在特定text.unfortunate之前和之后对值进行切片。例如,我需要得到如下
....发动机驱动程序包括在内,不仅仅是不幸的信号 - 男人对我一直困扰着他的话,还包括我自己的话......
答案 0 :(得分:1)
假设您的文本是divtxt然后使用此
var splitText=divtxt.split("unfortunate");
splitText [0]将在“unfortunate”之前显示文本,而splitText [1]将在“unfortunate”之后显示文本
答案 1 :(得分:0)
您可以使用indexOf()和substring()的组合。使用indexOf(“unfornate”)找到单词unfortunate的索引,然后使用该索引子串。
答案 2 :(得分: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 强>
答案 3 :(得分: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) + "...";
答案 4 :(得分:0)
根据更新的评论,你需要突出显示这个词,这样你就可以使用.replace()和一个简单的正则表达式
$('div').html(function(_, html){
return html.replace(/(unfortunate)/gi, '<b>$1</b>')
})
演示:Fiddle