将字符串插入动态位置的字符串中



我有一个包含一些颜色标签的字符串,看起来像这样:

[GREEN][BLUE][RED]

标签的位置可以不同。因此CCD_ 1可能在中间位置,也可能在最后位置。

现在我有一个新的颜色标签,应该添加到该列表中,让我们称之为[YELLOW]。所以[YELLOW]有一个动态的位置数,我们取变量const position = 2。这意味着[YELLOW]应该放在第二位,看起来应该是这样的:

[GREEN][YELLOW][BLUE][RED]

我该怎么做?

const text = "[GREEN][BLUE][RED]";
const inputNumber = 2;
const addingText = "[YELLOW]";
const index = text.split("[", inputNumber).join("[").length;
const output = [text.slice(0, index), addingText, text.slice(index)].join('');
console.log(output)

我会有一个占位符数组,如下所示:

const placeholders = ['[GREEN]', '[YELLOW]', '[BLUE]', '[RED]'];

当您需要在某个位置添加另一个占位符时,只需使用拼接功能:

placeholder.splice(position, 0, newPlaceholder);

然后,当你需要使用它时,你只需将其转换为字符串:

placeholder.join('');

我认为这将使它更容易处理,更可读,可能也更快。

您可以将.replace函数与以下正则表达式一起使用。

((?:[.*?]){2})

当您使用${variable}将变量插入regex时,您使用:

((?:\[.*?\]){${position-1}})

var listColors = "[GREEN][BLUE][RED]";
const position = 2;
var color = "[YELLOW]";

var pattern = `((?:\[.*?\]){${position-1}})`;
var regex = new RegExp(pattern);
var newListColors = listColors.replace(regex, `$1${color}`);
console.log(newListColors);

我会将其拆分为数组,然后在特定位置添加:

var text = "[GREEN][BLUE][RED]";
var matches = text.match(/[w+]/g);
matches.splice(1, 0, "[YELLOW]");
var result = matches.join("")
console.log(result);

https://www.w3schools.com/jsref/jsref_splice.asp

您应该找到第一个]出现的位置,然后连接[yellow]

最新更新