как разрезать текст перед определенным словом, используя JavaScript

0

Я получаю значение 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.

Мне нужно нарезать значение до и после определенного текста. Несомненно, это особое слово. Например, мне нужно получить как ниже

Водитель-двигатель включал не только слова, которые неудачный Сигнал-человек повторил мне, как преследующий его, но и слова, которые я сам....

  • 2
    почему ты хочешь это сделать
  • 0
    @ArunPJohny Я ищу слово в div. ir возвращает его полностью мне нужно нарезать содержимое до и после этого слова
Показать ещё 3 комментария
Теги:

5 ответов

0
Лучший ответ

На основе обновленных комментариев вам нужно выделить слово, чтобы вы могли использовать.replace() с простым регулярным выражением

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

Демо: скрипка

1

предположим, что ваш текст находится в divtxt, тогда используйте этот

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

splitText [0] будет иметь текст перед "неудачным", а splitText [1] будет иметь текст после "неудачного"

0

если вы want- ".... Engine-Driver включили не только слова, которые неудачный Сигнал-человек повторил мне, как преследуя его, но и слова, которые я сам..."

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) + "...";
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 («неудачный»), если вы хотите нарезать строку на «неудачное» слово.
0

Вы можете использовать комбинацию indexOf() и substring(). Найдите индекс слова неудачно, используя indexOf ("unfornate"), а затем подстроку, используя этот индекс.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню