我正在尝试将字符串转换为以某种方式输出,我认为最好的方法是使用模式匹配,但我遇到了一些问题。我不想打破字符串然后连接它。我希望有一种更简单的方法。我也遇到了一个问题(id)看来(id,)lastname后面的字符串文字取代了替换值
var myFunction - function(){
var str = "id,created,employee(id,firstname,employeeType(id), lastname),location";
var str2="id, created, employee";
var str3 = "(id,firstname,employeeType";
var str4="(id)";
var str5 ="lastname)";
var str6 = "location";
var test = str2.replace(/[,]/g, '<br>\r\n').split(",");
var test1 = str3.replace(/[(/,]/g, '<br>-\r\n').split(",");
var test2 =str4.replace(/[()/,]/g, '<br />--\r\n').split(",");
var test3 = str5.replace(/[,/)]/g, '<br />').split(",");
var test4 = str6.replace(/[)/,]/g, '<br />').split(",");
var result =test + test1 + test2 + test3 + test4 ;
var match = result.split(',')
document.getElementById("myDemo").innerHTML = match.join("<br />");;
}
myFunction()
我的输出如下所示
id
created
employee
- id
- firstname
- employeeType
-- id
-- lastname this should only be one dash not two
location
我做错了什么?
答案 0 :(得分:0)
这是一种将字符串作为时间遍历字符串的方法。遇到(
或)
时,计数器会递增或递减,表示应该有多少个-
个字符。
var stringFormatter = function() {
var str = "id,created,employee(id,firstname,employeeType(id), lastname),location";
var formatted = '';
var indentCount = 0;
var chars = str.split('');
chars.forEach(function(char) {
if (char == '(') {
indentCount++;
} else if (char == ')') {
indentCount--;
}
if (char == ',' || char == '(') {
formatted = formatted.concat('<br/>');
for (var i = 0; i < indentCount; i++ ) {
formatted = formatted.concat('-');
}
} else if (char != '(' && char != ')') {
formatted = formatted.concat(char);
}
});
document.getElementById("myDemo").innerHTML = formatted;
}
stringFormatter();
输出如下:
id
created
employee
-id
-firstname
-employeeType
--id
- lastname
location
答案 1 :(得分:0)
对于任何嵌套级别,您都可以使用此
var myFunction = function(){
var str = "id,created,employee(id,firstname,employeeType(id), lastname),location";
while(/\([^()]+\)/g.test(str))
{
m = /\(([^()]+)\)/g.exec(str);
m[1] = m[1].replace(/(-+)/g,"-$1");
m[1] = m[1].replace(/,/g,"-");
str = str.replace(/\(([^()]+)\)/,'-'+m[1]);
}
str = str.replace(/,/g,'<br>\r\n');
str = str.replace(/(-+)/g,'<br>$1 \r\n');
document.getElementById("myDemo").innerHTML += str + '</br>';
}
myFunction();
输出:
id
created
employee
- id
- firstname
- employeeType
-- id
- lastname
location
查看更多嵌套级别的结果
var str = "id,created,employee(id,firstname,contact(Mobile,Landline(home,office)),employeeType(id), lastname),location";
...
输出:
id
created
employee
- id
- firstname
- contact
-- Mobile
-- Landline
--- home
--- office
- employeeType
-- id
- lastname
location