2

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

5
  • 1
    A loop based method would be to use a loop and work on the string but not efficient maybe. Commented Aug 2, 2016 at 6:59
  • 2
    Remove the global flag g and repeat. str.replace(/_/, '(').replace(/_/,')') Commented Aug 2, 2016 at 6:59
  • Will you be getting only two brackets in all your string occurences? Commented Aug 2, 2016 at 7:00
  • @DavidR Not sure I need t replace the _ with brackets simultaneously Commented Aug 2, 2016 at 7:00
  • 1
    @tewathia, please add that as an answer.. so that I can mark it as accepted. It works perfectly for me. Commented Aug 2, 2016 at 7:10

6 Answers 6

4

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);

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks pranav... But I think str.replace(/_/, '(').replace(/_/,')') this one is more perfect
@Manu : it will only work if there if there is only 2 _ in string .... if more than 2 are there which only replace the first two.... otherwise which is perfect and simple :)
3

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>

Comments

1

Thats easy. Just a one liner needed.

testString = "AverageLogon_Seconds_";

replacedString = testString.replace(/_/, '(').replace(/_/, ')');

console.log(replacedString);

Output : "AverageLogon(Seconds)"

1 Comment

Keep in mind, that this only works for input with no more then two underscores. This answers the immediate question, but is not generally applicable.
1
var str = 'AverageLogon_Seconds_', replacement = ')';

//replace the last occurence  of '_' with ')'
str = str.replace(/_([^_]*)$/,replacement+'$1');

//replace the remaining '_' with '('
console.log(str);

Comments

1

Pranav's solution is nice. I tend to like to write things that I can very quickly reason about (i.e. 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_'));

1 Comment

They don't want you to answer questions on SO
-2

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--;
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.