I need help grabbing some string operation in Javascript. I have a sample string as
我需要帮助在Javascript中抓取一些字符串操作。我有一个示例字符串
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
该字符串基本上是两列的portlet配置,因为Supplier和Spend ..我必须从此字符串中获取列名。每颗星都遵循新的列配置。在这种情况下,只有2列的配置,因此我的字符串中只存在1个星。据说如果有2列,那么字符串就会像
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
所以从上面的字符串我写了一个逻辑来得到所需的字符串,因为我想要'供应商'(第一列数据名称而非第一列数据名称而不是'供应商(名称),这是一个显示名称),(之后移到第二列)在第二个插入符'花'之后。类似'Loc'(第3列)和'Categ'(第4列)。任何人都可以帮我实现这个目标吗?这是我写的
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 };
}
2 个解决方案
#1
3
You can use split()
你可以使用split()
str.split('*')[0].split('^')[1]
the above code will give you
上面的代码会给你
Supplier
Check the following link
请检查以下链接
#2
0
Or use a regular expression:
或者使用正则表达式:
function headers(s) {
var re = /([^^]+)(?:[^*]+[*]?)?/g, names=[];
while (match = re.exec(s)) {
names.push(match[1]);
}
return names;
}
Outputs ["Supplier","Spend (USD MM)","Location (Area)","Category "]
and ["Supplier (Name)","Spend (USD MM)","Location (Area)","Category "]
for your two examples
输出[“供应商”,“支出(美元MM)”,“位置(区域)”,“类别”]和[“供应商(名称)”,“支出(美元MM)”,“位置(区域)”,“类别“]为您的两个例子
See this in action (JSFiddle).
看到这个在行动(JSFiddle)。
#1
3
You can use split()
你可以使用split()
str.split('*')[0].split('^')[1]
the above code will give you
上面的代码会给你
Supplier
Check the following link
请检查以下链接
#2
0
Or use a regular expression:
或者使用正则表达式:
function headers(s) {
var re = /([^^]+)(?:[^*]+[*]?)?/g, names=[];
while (match = re.exec(s)) {
names.push(match[1]);
}
return names;
}
Outputs ["Supplier","Spend (USD MM)","Location (Area)","Category "]
and ["Supplier (Name)","Spend (USD MM)","Location (Area)","Category "]
for your two examples
输出[“供应商”,“支出(美元MM)”,“位置(区域)”,“类别”]和[“供应商(名称)”,“支出(美元MM)”,“位置(区域)”,“类别“]为您的两个例子
See this in action (JSFiddle).
看到这个在行动(JSFiddle)。