简体   繁体   中英

Make words from string matching with string bold

I want to make words matching in the string bold. I am using Jquery autocomplete with asp.net mvc. My following code works only if string has single word.

label = p.Name.Replace(termToSearch.ToLower(),"<b>" + termToSearch.ToLower() + "</b>"),

But doesnt work when I have 2 words matching which are at random position.

Eg When I search Gemini Oil

My Result should be id Gemini Sunflower Oil .

Any Ideas

A single line of Regex can do just that:

String term = "Gemini Oil";
String input = "Gemini Sunflower Oil.";
String result = Regex.Replace( input, String.Join("|", term.Split(' ')), @"<b>$&</b>");
Console.Out.WriteLine(result);


<b>Gemini</b> Sunflower <b>Oil</b>.

You could just split the search term on each space character and then run the replace multiple times:

var terms = termToSearch.split(' ');
foreach (var term in terms) {
    p = p.Name.Replace(term.ToLower(),"<b>" + term.ToLower() + "</b>"),
}
label = p;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM