1

I have a task. I need to highlight specific words in income HTML. To find the exact word i need to use its coordinates. Coordinates are calculating according to word`s first and last letter position in the string.

Example

I have such constant

const exmpleString: string = `<h1>Name</h1> <p>Some some, text some.</p>`;

I need to highlight word text. Its coordinates is [28,31] - because first t is on position 28 in the string and last t is on position 31.

I found out how to make it with regex.

const testString: string = 'some some some text some some text';
const keyWord: string= 'text';
const regexRule: any = new RegExp(keyWord, 'g');

const result: string = testString.replace(regexRule, `<span class="some">${keyWord}</span>`);
console.log(result);

Works great but i need other solution.

  • Why do you not want to use the solution using a regular expression? – NineBerry Jan 31 '19 at 11:19
  • if the string already has HTML format before, you should consider that the keyword may appear in places of the string that you cannot or do not want to highlight. For example, what if the keyword is "div"? Or what when the keyword appears in the title attribute of a tag or in a filename of a referenced image etc.. – NineBerry Jan 31 '19 at 11:20
  • Yes, you are right. The way with regex is great but in my case the point is to avoid it( – Yura Lukashchuk Jan 31 '19 at 12:05

3 Answers3

2

Obtain coordinates as testString.indexOf(keyWord) and testString.indexOf(keyWord)+ keyWord.length.

Then splice.

Or just replace

testString.replace(keyWord, `<span class="some">`+keyWord+`</span>`)
Attersson
  • 4,755
  • 1
  • 15
  • 29
0

Problem in that solution is it messes up when the string to be highlighted has "<,>,&lt" ~ HTML characters. you can find it in my question here or You can use mark.js - https://markjs.io/

var context = document.querySelector(".context");
var instance = new Mark(context);
instance.mark('line');
<script src="https://cdnjs.cloudflare.com/ajax/libs/mark.js/8.10.0/mark.min.js"></script>


<div class="context">
this is a test line used to explain mark.js
</div>
-1

I don't use TypeScript so I would write an alternate solution to your and attersson in Javascript

const HighlightedText = (start, end, givenString) => {
  let someString = givenString.split("")
  let highlightedText = []
  for (let i=start; i<=end; i++) {
    highlightedText.push(someString[i+1])
  }
   return highlightedText
}


let HighlightText = HighlightedText(28, 31, "some some some text some some text")

console.log(HighlightText)

And then you can highlight it.

Ps: I am not sure how t is at position 28

Alwaysblue
  • 9,948
  • 38
  • 121
  • 210