How to highlight a substring containing a random character between two known characters using javascript?
Asked Answered
T

2

0

I have a bunch of strings in a data frame as given below.

             v1                    v2
ARSTNFGATTATNMGATGHTGNKGTEEFR   SEQUENCE1
BRCTNIGATGATNLGATGHTGNQGTEEFR   SEQUENCE2
ARSTNFGATTATNMGATGHTGNKGTEEFR   SEQUENCE3

I want to search and highlight some selected substrings within each string in v1 column. For example, assuming first letter in the substring being searched as "N" and the last letter as "G", and the middle one could be any letter as in "NAG" or "NBG" or "NCG" or "NDG" and so on. To highlight the substring of three characters as shown below, I am writing 26 lines of code to display in R Shiny tab assuming there could be any of the 26 letters in between "N" and "G". I am just trying to optimize the code. I am new to JS. Hope I was clear. If not before down voting please let me know should you need more explanation or details.

ARSTNFGATTATNMGATGHTGNKGTEEFR

BRCTNIGATGATNLGATGHTGNQGTEEFR

ARSTNFGATTATNMGATGHTGNKGTEEFR

The abridged code with representative 2 lines (first and last line) of the 26 lines of the code I use are provided here.

datatable(DF, options = list(rowCallback=JS("function(row,data) {
  data[0] = data[0].replace(/NAG/g,'<span style=\"color:blue; font-weight:bold\">NAG</span>');
  .....
  data[0] = data[0].replace(/NZG/g, '<span style=\"color:blue; font-weight:bold\"\">NZG</span>');
  $('td:eq(0)', row).html(data[0]);}"), dom = 't'))
Tenebrous answered 19/11, 2016 at 20:34 Comment(0)
T
1

I found a simple solution. May be it will be useful to someone like me.

datatable(DF, options = list(rowCallback = JS("function(row,data) {
    data[0] = data[0].replace(/N[A-Z]G/g,'<span style=\"color:blue; font-weight:bold\">$&</span>');
    $('td:eq(0)', row).html(data[0]);}"), dom = 't'))
Tenebrous answered 23/11, 2016 at 6:23 Comment(0)
S
2

I think the regex you want is: /N[A-Z]G/g

If you also want it to work for lower case: /N[A-Za-z]G/g

Scrutineer answered 19/11, 2016 at 20:39 Comment(2)
How to represent the replacement string? >NxG<. Should it be >N[A-Za-z]G<?Tenebrous
The replacement string replaces everything that was matched by the regex, so you'd have to include the N and the G and whatever you want in between them.Scrutineer
T
1

I found a simple solution. May be it will be useful to someone like me.

datatable(DF, options = list(rowCallback = JS("function(row,data) {
    data[0] = data[0].replace(/N[A-Z]G/g,'<span style=\"color:blue; font-weight:bold\">$&</span>');
    $('td:eq(0)', row).html(data[0]);}"), dom = 't'))
Tenebrous answered 23/11, 2016 at 6:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.