gpt4 book ai didi

javascript - 向后循环直到找到某个字符(javascript)

转载 作者:行者123 更新时间:2023-11-28 18:09:26 25 4
gpt4 key购买 nike

我有一个情况,我有一个字符串数组,并且想将字符附加到数组中括号之间的字符串部分。

例如,如果我的数组是:

['Lorem', '(ipsum', 'dolor', 'sit)', 'amet', 'consectetur', 'adipiscing', 'elit']

我想返回类似的内容:

['Lorem', '(ipsum-foo', 'dolor-foo', 'sit-foo)', 'amet', 'consectetur', 'adipiscing', 'elit']

编辑:

大家好,我很抱歉没有添加我的初始代码。它包含在很多其他内容中,但目前看起来像这样:

                // other stuff up above (incl. a backwards loop k)  
else {
// if it has a certain ending, save to mostRecentTag
if (notArray[k].search(/\./) >= 0) { //
var mostRecentTagArray = notArray[k].match(/\.[a-zA-Z,/-]+/);
mostRecentTag = mostRecentTagArray[0]; // mostRecentTag = keyword field code
}
// if doesn't meet criteria above, change ending to .af
else if (mostRecentTag == "") { // TO DO fix this line: (exercise OR physical.ti) --> "exercise"[ti] OR "physical"[ti]
notArray[k] = notArray[k] + ".af";
}
// adds mostRecentTag to the end
else {
notArray[k] = notArray[k] + mostRecentTag;
}

(这是更大片段的部分剪辑)

但是,就目前情况而言,表达式如下:

锻炼 OR((锻炼 OR 体力).ti OR 体力)

将更改为:

运动[ti] OR ((运动[ti] OR 物理[ti]) OR 物理)

而我更希望它的计算结果为:

锻炼 OR ((锻炼[ti] OR 体力[ti]) OR 体力)

我希望这一切都有意义,对于部分且令人困惑的代码,我深表歉意。

最佳答案

解决此类问题的方法有很多种,但一般来说,您需要隔离目标子字符串,修改它,然后用修改后的值替换原始值。实现此目的的一种方法是使用正则表达式来匹配子字符串。

JSFiddle:https://jsfiddle.net/agqb8ycd/

var arr = ['Lorem', '(ipsum, dolor, sit)', 'amet', 'consectetur', 'adipiscing', 'elit'];
var tester = /\((.*)?\)/; // Find strings which contain parens () that contain characters i.e., (adsf)

// Operate on the array
arr.forEach(function (content, i) {
var matchedContent = content.match(tester);

// Noop strings that don't match the tester
if (!matchedContent) {
return;
}

// Now we'll need to operate on those substrings within the parens individually. In this case they are separated by commas, so the most simple way is to break the string into an array of strings and mutate them.
var substrings = matchedContent[1].split(',');

// Mutate the substrings
substrings = substrings.map(function (substring) {
return substring + '-foo';
});

// Since we matched on the group within the regular expression, we will have to restore the parens lost by the matcher
var mutatedContent = '(' + substrings.join(', ') + ')';

// Overwrite the original value in the array
arr[i] = mutatedContent;
});

关于javascript - 向后循环直到找到某个字符(javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41946260/

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