如何找到匹配子字符串的值

时间:2014-04-29 13:02:23

标签: javascript string

我想实现一个函数,它将使用字符串

返回匹配的变量数组

例如

str = 'abcSSSdefghEEEijSSSkEEElmnSSSEEEop';
matching = abcSSSvar1EEEijSSSvar2EEElmnSSSvar3EEEop;

函数应该接受四个参数

str : main string
matching : string with variables
start : start of the var, in above case start = 'SSS';
end : end of the var, in above case = 'EEE';

函数应返回数组返回键值映射

在上述情况下应返回

{
  "var1" : "defgh",
  "var2" : "k",
  "var3" : ""
}

如何在javascript中有效地实现上述

1 个答案:

答案 0 :(得分:1)

是否有与strmatching相关联的保证?

此解决方案在假设将提供与键一样多的值的情况下运行。

/**
 * Extracts variables from the input string using the start and
 * end as splitters.
 */
var extractVariables = function(input, start, end) {
    var arr = [];
    var i = 0;
    while (i < input.length) {
        if (input.substring(i, i + start.length) == start) {
            var v = "";
            for (var j = i + start.length; j < input.length; j++) {
                if (input.substring(j, j + end.length) == end) {
                    arr[arr.length] = v;
                    break;
                }
                v += input[j];
            }
            i = j;
        } else {
            i++;
        }
    }
    return arr;
}

/**
 * Extracts keys from matching, values from str, and populates 
 * a map with the variables. The map will only have as many entries
 * as keys provided.
 */
var buildVarMap = function(str, matching, start, end) {
    var map = {};
    var values = extractVariables(str, start, end);
    var keys = extractVariables(matching, start, end);
    for (var k = 0; k < keys.length; k++) {
        map[keys[k]] = values[k];
    }
    return map;
}

var varMap = buildVarMap(
    "abcSSSdefghEEEijSSSkEEElmnSSSEEEop", 
    "abcSSSvar1EEEijSSSvar2EEElmnSSSvar3EEEop", 
    "SSS", 
    "EEE"
);

fiddle