注意: 在此時,我無法更好地將問題標題更改。如果有人能夠更好地交流,請繼續前進!在每個特定子字符串的出現處剪切JS字符串並追加到相同的數組
我有什麼:
var array = ["authentication.$.order", "difference.$.user.$.otherinformation", ... , ...]
我需要什麼:
["authentication", "authentication.$", "authentication.$.order",
"difference", "difference.$", "difference.$.user", "difference.$.user.$",
"difference.$.user.$.otherinformation"]
基本上,wherevever我看到.$.
,我需要保留它,那麼的occourrence前追加一切.$.
以及.$
的所有內容
例子:
difference.$.user.$.otherinformation
應該解釋爲包含:
difference
difference.$
difference.$.user
difference.$.user.$
difference.$.user.$.otherinformation
我強烈的感覺,某種遞歸這裏要參與,但在方向上沒有進展呢。
下面是我的實現相同,但不幸的是,當我的子字符串匹配第一次發生的.$.
時,它停止並且不會繼續檢查同一字符串中的其他出現.$.
。
我該如何最好地把這個關閉?
當前有缺陷的實現:
for(var i=0; i<array.length; i++){
// next, replace all array field references with $ as that is what autoform's pick() requires
// /\.\d+\./g,".$." ==> replace globally .[number]. with .$.
array[i] = array[i].replace(/\.\d+\./g,".$.");
if(array[i].substring(0, array[i].lastIndexOf('.$.'))){
console.log("Substring without .$. " + array[i].substring(0, array[i].indexOf('.$.')));
console.log("Substring with .$ " + array[i].substring(0, array[i].indexOf('.$.')).concat(".$"));
array.push(array[i].substring(0, array[i].indexOf('.$.')).concat(".$"));
array.push(array[i].substring(0, array[i].indexOf('.$.')));
}
}
// finally remove any duplicates if any
array = _.uniq(array);
迄今爲止就緊湊性而言最短的答案,但在可理解性方面複雜。你能否解釋這實際上是如何工作的? – blueren
如果數組包含如下值:'「www.example.com。」'? – hindmost
@ behindmost - 好問題,但我的初始數組永遠不會包含以'''''''結尾的內容,所以我認爲這是安全的。 – blueren