Antoine Guenet
Antoine Guenet

Reputation: 108

Insert character in string before each group of digits

I have a string that can have this form: "4 4 8 16 16" but can also use another separator like so: "4, 4, 8, 16, 16" or "4-4-8-16-16". I'd like to make it into this: "C/4 C/4 C/8 C/16 C/16". When using str.replace(/(?=\d)/g, 'C/'), I get the following wrong result: "C/4 C/4 C/8 C/1C/6 C/1C/6". Does anybody have a solution? Using a for loop seems to get very inefficient very quickly when the string gets bigger.

Upvotes: 2

Views: 42

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386570

You could replace all non numerical values with the wanted parts and while it has a leading space, you need to slice the result.

var array = ["4 4 8 16 16", "4, 4, 8, 16, 16", "4-4-8-16-16"];

console.log(array.map(s => s.replace(/^|\D+/g, ' c/').slice(1)));

An other proposal with splitting and reassembling the parts.

var array = ["4 4 8 16 16", "4, 4, 8, 16, 16", "4-4-8-16-16"];

console.log(array.map(s => s
    .split(/\D+/)
    .map(s => 'C/' + s)
    .join(' ')
));

Upvotes: 4

Related Questions