【发布时间】:2025-12-29 18:10:10
【问题描述】:
我想拆分一个字符串,比如:
"Hello $id1, how are you $id2 etc...",
但是“$idInt”不应该被拆分:
const test = [
"$id1",
"$id2",
"$id3"
]
let str = "test $id1!";
str = str.split("");
// wanted result: ["t", "e", "s", "t", " ", "$id1", "!"];
// actual result: ["t", "e", "s", "t", " ", "$", "i", "d", "1" "!"]
这将从“测试”数组中获取任何内容,而不是将其与每个单独的字符分开。
我只搜索了其他资源,但我还没有找到完全符合我要求的东西。
我也得到了这个代码:
let reg = /\%\[a-zA-Z0-9]\:[0-9]+\%/gim;
let yourstring = 'Some thinger %09ff:13%';
let matches = reg.exec(yourstring);
let records = [];
let pieces = [];
if (matches != null) {
for (let [i, match] of Array.from(matches).entries()) {
let start = yourstring.indexOf(match);
let end = match.length + start;
records.push({
start: start,
end: end,
match: match,
});
}
records.sort((a, b) => (a.start > b.start ? 1 : a.start < b.start ? -1 : 0));
if (records[0].start > 0) {
records = [{
start: 0,
end: 0,
match: ""
}].concat(records);
}
for (let i = 1; i < records.length; i++) {
pieces.push(yourstring.slice(records[i - 1].end, records[i].start).replace(......)); // replace goes here
pieces.push(records[i].match);
}
yourstring = pieces.join("")
} else {
yourstring = yourstring.replace(.......) // replace goes here
}
但它是正则表达式,我希望一组字符串不被替换,而不是这里用正则表达式替换
【问题讨论】:
-
* 不是免费的编码服务。你应该try to solve the problem first。请更新您的问题以在minimal reproducible example 中显示您已经尝试过的内容。如需更多信息,请参阅How to Ask,并拨打tour :)
标签: javascript arrays split