Edge7
Edge7

Reputation: 681

Change char in a string in JavaScript

What regular expression should I use with the 'replace()' function in JavaScript to change every occurrence of char '_' in 0, but stop working as long as finding the char '.'?

Example:

_____323.____ ---> 00323._

____032.0____ --> 0032.0_

Are there ways more efficient than to use 'replace()'?

I am working with numbers. In particular, they can be both integer that float, so my string could never have two dots like in __32.12.32 or __31.34.45. At maximum just one dot.

What can I add in this:

/_(?=[\d_.])/g

to also find '_' followed by nothing?

Example: 0__ or 2323.43_

This does not work:

/_(?=[\d_.$])/g

Upvotes: 3

Views: 284

Answers (5)

user557597
user557597

Reputation:

Unless you have some other obscure condition -

find:

 _(?=[\d_.])

replace:

 0

Or "To find also _ followed by nothing, example: 0__ or 2323.43_"

_(?=[\d_.]|$)

Upvotes: 1

Billy Moon
Billy Moon

Reputation: 58531

var str = "___345_345.4w3__w45.234__34_";

var dot = false;
str.replace(/[._]/g, function(a){
  if(a=='.' || dot){
    dot = true;
    return a
  } else {
    return 0
  }
})

Upvotes: 0

Aegis
Aegis

Reputation: 1789

Without replace/regex:

var foo = function (str) {
  var result = "", char, i, l;
  for (i = 0, l = str.length; i < l; i++) {
    char = str[i];
    if (char == '.') {
      break;
    } else if (char == '_') {
      result += '0';
    } else {
      result += str[i];
    }
    char = str[i];
  }
  return result + str.slice(i);
}

With regex: dystroy

Benchmark for the various answers in this post: http://jsperf.com/regex-vs-no-regex-replace

Upvotes: 1

Billy Moon
Billy Moon

Reputation: 58531

You could use lookahead assertion in regex...

"__3_23._45_4".replace(/_(?![^.]*$)/g,'0')

Result: 003023._45_4

Explanation:

/          # start regex
_          # match `_`
(?!        # negative lookahead assertion
[^.]*$     # zero or more (`*`) not dots (`[^.]`) followed by the end of the string
)          # end negative lookahead assertion
/g         # end regex with global flag set

Upvotes: 0

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382132

You could use

str = str.replace(/[^.]*/,function(a){ return a.replace(/_/g,'0') })

Reference

Upvotes: 8

Related Questions