user3585284
user3585284

Reputation: 59

how to find with which value a substring was matched

I want to implement a function that will return the matched variables array from with a string

for example

str = 'abcSSSdefghEEEijSSSkEEElmnSSSEEEop';
matching = abcSSSvar1EEEijSSSvar2EEElmnSSSvar3EEEop;

function should accept four parameters

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';

function should return array return key value maps

in above case should return

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

How to efficently implement above in javascript

Upvotes: 0

Views: 66

Answers (1)

Sam Berry
Sam Berry

Reputation: 7844

Are there any guarantees associated with str and matching?

This solution operates under the assumption that there will be as many values provided as there are keys.

/**
 * 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

Upvotes: 1

Related Questions