gpt4 book ai didi

javascript - 如何查找子字符串与哪个值匹配

转载 作者:行者123 更新时间:2023-12-03 12:45:23 25 4
gpt4 key购买 nike

我想实现一个函数,它将用字符串返回匹配的变量数组

例如

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中高效实现上述内容

最佳答案

是否存在与 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

关于javascript - 如何查找子字符串与哪个值匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23365448/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com