0

I need help grabbing some string operation in Javascript. I have a sample string as

var str = 'Supplier^supp^left^string*Spend (USD MM)^spend^right^number^5';

The string is basically a configuration for a portlet for two columns as Supplier and Spend..I have to get the column names from this string. Each star follows a new column config. In this case there are configs for only 2 columns and hence only 1 star exists in my string. Supposedly if there are 2 columns the string will look like

var str = 'Supplier (Name)^Supplier^left^string*Spend (USD MM)^Spend^right^number^5*Location (Area)^Loc^right^string^*Category ^Categ^right^string';

So from the above string i had written a logic to get the desired string as after the 2nd caret i want 'Supplier'(1stcolumn data name and not 'Supplier (Name) which is a display name) ,(Moving to 2nd column after the star)after the 2nd caret 'Spend'.Similarly 'Loc' (3rd column) and 'Categ' (4th column). Can anybody help me achieve this? Here is what i had written

    function getColNamesfromConfig(str) {
        var i = str.indexOf('^');
        var tmpCatStr = str.slice(i + 1);
        var catField = tmpCatStr.slice(0, tmpCatStr.indexOf('^'));

        var j = tmpCatStr.indexOf('*');
        var tmpStr = tmpCatStr.slice((j + 1));
        var k = tmpStr.slice(tmpStr.indexOf('^') + 1);
        var valField = k.slice(0, k.indexOf('^'));
        return { categoryField: catField, valueField: valField };
    }
4

2 回答 2

3

您可以使用split()

str.split('*')[0].split('^')[1]

上面的代码会给你

Supplier

检查以下链接

于 2012-07-25T08:13:30.260 回答
0

或者使用正则表达式:

   function headers(s) {
      var re = /([^^]+)(?:[^*]+[*]?)?/g, names=[];
      while (match = re.exec(s)) {
        names.push(match[1]);
      }
      return names;
   }

输出 ["Supplier","Spend (USD MM)","Location (Area)","Category "]["Supplier (Name)","Spend (USD MM)","Location (Area)","Category "] 你的两个例子

看这个实际操作(JSFiddle)。

于 2012-07-25T08:32:42.110 回答