0

I would like the search a string without case sensitive however change the sub string with original string's case letters.

var mystring = "FiRst Last";
var term = "first";  // it could be "FIRST" or fIRST

var re = new RegExp("^" + term, "i") ;
//option 1
//var t = mystring.replace(re,"<span style='font-weight:bold; color:Blue;'>" + term + "</span>");
//option 2
var t = mystring.replace(re,term.bold().fontcolor("Blue"));

The above code gives first LAST in blue color, however i want it to be FiRst LAST as mystring's case order

maybe indexof() method can be used however there might be an easy efficient way.

aliaktas
  • 165
  • 10
  • In other words, you need all your string uppercased, but the words matched by `term` left intact? – raina77ow Dec 12 '12 at 11:15
  • 1
    See this it may helpful.... [http://stackoverflow.com/questions/3294576/javascript-highlight-substring-keeping-original-case-but-searching-in-case-inse][1] [1]: http://stackoverflow.com/questions/3294576/javascript-highlight-substring-keeping-original-case-but-searching-in-case-inse – R D Dec 12 '12 at 11:26

2 Answers2

1
var querystr = 'first';
var output = "FiRst Last";
var reg = new RegExp(querystr, 'gi');
var final_str = output.replace(reg, function(str) {return str.bold().fontcolor("Blue")});

See this following link...

Javascript: highlight substring keeping original case but searching in case insensitive mode

Solution give by user113716 may helpful...

Community
  • 1
  • 1
R D
  • 1,330
  • 13
  • 30
  • any way to work this code with Turkish characters. for example: querystr ='istanbul' output = "İstanbul Turkey" – aliaktas Dec 12 '12 at 21:17
0

Just use a capture group with your first option

var str = "FiRst Last";
var term = "first";

var t = str.replace( /(first)/i, "<span style='font-weight:bold; color:Blue;'>$1</span>");

t will now contain

"<span style='font-weight:bold; color:Blue;'>FiRst</span> Last"
Bruno
  • 5,772
  • 1
  • 26
  • 43