I have a string AverageLogon_Seconds_
I need to replace the first underscore with '('
and second Underscore with ')'
.
Means I need to get the text like AverageLogon(Seconds)
.
I have checked with str.replace(/_/g, ')');
, but it will replace both the underscore iwth ')'.
Can anyone help me on this.
Thanks
Do it with String#replace
with a callback and a counter variable. Replace _
with (
in an odd position and )
in an even position where the counter variable can be used for finding out the position.
var str = 'AverageLogon_Seconds_', i = 0; var res = str.replace(/_/g, function() { return i++ % 2 == 0 ? '(' : ')'; }); console.log(res);
I feel like it would be more prudent to target the "_something_"
pattern as a whole. Something like
str.replace(/_([a-z0-9 -]+)_/gi, '($1)')
You can narrow that [a-z0-9 -]
character class down based on the characters you expect to appear between the underscores. For now, I've got letters, numbers, spaces and hyphens.
var tests = [ 'AverageLogon_Seconds_', 'AverageLogon_Seconds_ and some other_data_', 'Oh no, too_many_underscores___'], out = document.getElementById('out'), rx = /_([a-z0-9 -]+)_/gi; tests.forEach(function(test) { out.innerHTML += test + ' => ' + test.replace(rx, '($1)') + '\\n'; });
<pre id="out"></pre>
var str = 'AverageLogon_Seconds_', replacement = ')';
//replace the last occurence of '_' with ')'
str = str.replace(/_([^_]*)$/,replacement+'$1');
//replace the remaining '_' with '('
console.log(str);
Thats easy. Just a one liner needed.
testString = "AverageLogon_Seconds_";
replacedString = testString.replace(/_/, '(').replace(/_/, ')');
console.log(replacedString);
Output : "AverageLogon(Seconds)"
Pranav's solution is nice. I tend to like to write things that I can very quickly reason about (ie sometimes less elegant). Another way (read in DJ Khaled's voice):
function replaceUnderscores(str) { return str.split('_').map(function (part, ind) { if (part === '') { return ''; } if (ind % 2 === 0) { return part + '('; } else { return part + ')'; } }).join(''); } // "AverageLogon(Seconds)" console.log(replaceUnderscores('AverageLogon_Seconds_'));
will this work
var t = "AverageLogon_Seconds_";
var ctr=0;
while(t.contains('_')){
if(ctr==0){
t= t.replace('_','(');
ctr++;
}
else{
t= t.replace('_',')');
ctr--;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.