Learning
Learning

Reputation: 20001

Last item in the c# list

I am need to highlight the keywords or tags in an article & pass variable to jQuery Array i am using property to pass value from C# to java-script which works i also need to format my keywords which in database are stored like one, two, three, four, five,six,seven

in order to make it work i have to wrap each keyword in single ' or double quotes".

JQuery

    function HighlightKeywords(keywords) {
        var el = $("body");
        $(keywords).each(function () {
            var pattern = new RegExp("(" + this + ")", ["gi"]);
            var rs = "<a href='search.aspx?search=$1'<span style='background-color:#FFFF00;font-weight: bold;background-color:#FFFF00;'>$1</span></a>";
            el.html(el.html().replace(pattern, rs));
        });
    }

HighlightKeywords(["<%= MyProperty %>]");

C# Code

string _sFinalList = null;

protected string MyProperty { get { return _sFinalList; } }
string sKewords = "one, two, three, four, five,six,seven";

List<string> lstKewords = sKewords.Split(',').ToList();
foreach (string list in lstKewords) // Loop through List with foreach
{
   _sFinalList += "'" + list + "',";

}

Problem with this code is that it ads , after the last words i want to know what is the best way to avoid adding , after the last words

Current OUTPUT: "'one', 'two', 'three', 'four', 'five','six','seven',"

Desired OUTPUT: "'one', 'two', 'three', 'four', 'five','six','seven'"

Help in this regard is appreciated

Upvotes: 0

Views: 620

Answers (4)

Henk Holterman
Henk Holterman

Reputation: 273264

In C#, use String.Join() :

List<string> lstKeywords = sKeywords.Split(',').ToList();

var quotedKeywords = lstKeywords.Select(s => "'" + s + "'");

string _sFinalList = string.Join(",", quotedKeywords);

Upvotes: 3

relativelyPrime
relativelyPrime

Reputation: 171

you may simply remove lastIndexOf(",") with substring function of string class after you complete the for loop.

OR

you may add and if statement in your for loop that would add "," if loop is not in its last iteration.

Upvotes: 0

Ash Burlaczenko
Ash Burlaczenko

Reputation: 25445

You could use String.Join

var result = string.Format("'{0}'", string.Join("','", yourList));

Upvotes: 1

John Woo
John Woo

Reputation: 263723

You can using String.Join()

string sKewords = "one, two, three, four, five,six,seven";
List<string> lstKewords = sKewords.Split(',').ToList();
var _partial = lstKewords.Select(x => "'" + x + "'");
Var _result = String.Join(",", _partial);

Upvotes: 1

Related Questions