如果缺少字符串,如何插入括号和值?

use*_*031 0 javascript regex jquery

这里我有逗号字符串组,如"stack,flow(2),over(4),temp(0)"如果只是没有打开和关闭括号值的字符串,我需要插入with(1).堆(1).

Expected scenario :

1.insert (1) missing open & close parentheses 
2.within parentheses should be >0 numeric values.
3.within parentheses if any alpha character , show error message.
Run Code Online (Sandbox Code Playgroud)

因为我需要验证在括号中的值应该是数字.我尝试了一些scenrio,但我需要帮助插入(1).

function testCases(str){
    return (
    str.match(new RegExp("\\([^,]+\\)","g")).length  == str.split(",").length
    );
}
Run Code Online (Sandbox Code Playgroud)

这是jsfiddle

Den*_*ret 5

如果我正确理解你想(1)在逗号之前插入,如果没有括号组,那么你可以这样做:

var str = "stack,flow(2),over(4),temp(0)";
str = str.replace(/([^)]),/g, "$1(1),");
Run Code Online (Sandbox Code Playgroud)

结果: "stack(1),flow(2),over(4),temp(0)"

如果您还想确保该组包含严格正整数,您可以这样做

var str = "stack,flow(2),flow(k),over(4),neg(-3),temp(0)";
str = str.split(',').map(function(s){
    return s.replace(/(\((.*?)\))?$/, function(s,d,e) {
        return '('+ (e>0?e:1)+')'
    })
}).join(',');
Run Code Online (Sandbox Code Playgroud)

结果: "stack(1),flow(2),flow(1),over(4),neg(1),temp(1)"