i want to ask how to manipulate char in string depends on giving value
my string
"---x---x---x------x"
when im input a value = 2
char "x" was changed to "o" in 2 times
my expected value is
"---o---o---x------x"
thank you in advance
CodePudding user response:
based on solution here:
var str = "---x---x---x------x"
var n = 0
var N = 2
var newStr = str.replace(/x/g,s => n <N ? 'o' : s)
CodePudding user response:
const x = "---x---x---x------x";
let input = 2;
let output = [];
for (const dashes of x.split("x")) {
output.push(dashes);
if (input > 0) {
input--;
output.push("o");
} else {
output.push("x");
}
}
output.pop();
output = output.join("");
console.log({ output });
CodePudding user response:
You can just loop over the and replace x
with o
until value
becomes 0
(which is falsy value)
let str = "---x---x---x------x";
let value = 2;
while (value--) {
str = str.replace("x", "o");
}
console.log(str);