Racialz Racialz - 10 months ago 29
Javascript Question

Highlighting a specific area of a grid containing <br> and reformatting the grid

I have a string that looks like this


It's really a grid that looks like this without the newlines (just has
, no actual newlines (\n))


I want to bold a certain section of this grid that can change every time, for this example lets say I want to bold 8617. (This number could be longer and stretch multiple lines, my actual grid is much larger)

I want it to appear like this:





I tried using this (maxStr is the string of numbers I want to replace)

gridString.replace(maxStr, "<strong>" + maxStr + "</strong>")

But that won't work because the string has
in it, so the string I actually have to replace is

My question is: how can I replace a certain portion of numbers that stretch across multiple lines with their bold version while keeping the
where I need it.

JSFiddle illustrating my problem: https://jsfiddle.net/5d21c2r3/

Side note: I tried a solution where I removed all
from my grid, then replaced the text, then re-added
every 50 characters, but that didn't work either because the
end up adding a lot of characters.


You can make a regex that allows optional <br> between any number:

var toReplace = "8617";

var regex = new RegExp("(" + toReplace.split("").join("(?:<br>)?") + ")")

document.write(gridString.replace(regex, "<strong>$1</strong>"))

See updated JS Fiddle.


The regex produced is /(8(?:<br>)?6(?:<br>)?1(?:<br>)?7)/. (?:) is a non-capturing group. ? after it means that it's optional — it can appear zero or one times. The ( at the beginning and ) at the end is a capturing group — it allows you to use the matched substring later as $1.