I have a string that looks like this
16427171479924442928230863465674813919123162824586<br>17866458359124566529476545682848912883142607690042<br>2421902671055626321111109370544217506941658960408<br>07198403850962455444362981230987879927244284909188<br>
It's really a grid that looks like this without the newlines (just has<br>
, no actual newlines (\n))
16427171479924442928230863465674813919123162824586<br>
17866458359124566529476545682848912883142607690042<br>
24219022671055626321111109370544217506941658960408<br>
07198403850962455444362981230987879927244284909188<br>
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:
16427171479924442928230863465674813919123162824586
17866458359124566529476545682848912883142607690042
24219022671055626321111109370544217506941658960408
07198403850962455444362981230987879927244284909188
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 <br>
in it, so the string I actually have to replace is 86<br>17
My question is: how can I replace a certain portion of numbers that stretch across multiple lines with their bold version while keeping the <br>
where I need it.
JSFiddle illustrating my problem: https://jsfiddle.net/5d21c2r3/
Side note: I tried a solution where I removed all <br>
from my grid, then replaced the text, then re-added <br>
every 50 characters, but that didn't work either because the <strong>
and </strong>
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With