问题
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'))
回答1:
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
回答2:
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'))
来源:https://stackoverflow.com/questions/40697627/how-to-highlight-a-substring-containing-a-random-character-between-two-known-cha