-2

I have a string that includes some color tags, that looks like this:

[GREEN][BLUE][RED]

The position of the tags can be different. So [GREEN] could be in middle or in the last position as well.

Now I have a new color tag that should be added to that list, let's call it [YELLOW]. So [YELLOW] has a dynamic position number, let's take the variable const position = 2. Well, that means that [YELLOW] should be placed in second place, which should look like this:

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

How can I do this?

Proseller
  • 113
  • 1
  • 8
  • You should array instead regex, it will be a lot easier when you have tags with special characters or in words like `That's Him`. you can see example [here](https://stackoverflow.com/questions/586182/how-to-insert-an-item-into-an-array-at-a-specific-index-javascript?answertab=active#tab-top) – Noman Nov 05 '20 at 13:34
  • Can you please check this post https://stackoverflow.com/questions/4364881/inserting-string-at-position-x-of-another-string – 04k Nov 05 '20 at 13:35

5 Answers5

1

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)
wangdev87
  • 8,611
  • 3
  • 8
  • 31
1

I would have an array of placeholders like this:

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

When you need to add another placeholder in a certain position you simply use the splice function:

placeholder.splice(position, 0, newPlaceholder);

Then when you need to use it, you just convert it to a string:

placeholder.join('');

I think this would make it much easier to handle, more readable and possibly quicker too.

eloyra
  • 519
  • 2
  • 6
1

I would split this to array and then add at specific position:

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

Mateusz Marchel
  • 772
  • 4
  • 14
1

You could use .replace function with the following regex.

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

When you insert variable to regex using${variable}, you use:

((?:\\[.*?\\]){${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);
Thân LƯƠNG Đình
  • 3,082
  • 2
  • 11
  • 21
0

You should find in which possition the first ] appears and then concat the [yellow]

04k
  • 175
  • 2
  • 8