Suppose I have a string like this: "a_b_c_d_restofthestring"
and I want to keep only 2 underscores. For example,
"a_b_cdrestofthestring"
"abc_d_restofthestring"
Both of these are valid outputs.
This is my current implementation:
let str = "___sdaj___osad$%^&*";
document.getElementById('input').innerText = str;
let u = 0;
str = str.split("").reduce((output, c) => {
if (c == "_") u++;
return u < 2 || c != "_" ? output + c : output;
});
document.getElementById('output').innerText = str;
<div id="input"></div>
<div id="output"></div>
I'm wondering if there's a more efficient way to achieve this...