Mark Puchala II
Mark Puchala II

Reputation: 652

Does .replace not work in a for loop?

So I'm trying to just make a ".replace" loop, but something mysterious is happening.

var cell = "r1c1";

for (i = 0; i <= 4; i++){
  cell = cell.replace(cell[3],i+1);

My expected output:

cell = "r1c1"
cell = "r1c2"
cell = "r1c3"
cell = "r1c4"
cell = "r1c5"

The actual output:

cell = "r1c2"
cell = "r2c1"
cell = "r2c3"
cell = "r2c4"
cell = "r2c5"

As you can see, it runs normal EXCEPT for the second iteration. What in the world am I doing so wrong?

Upvotes: 1

Views: 479

Answers (3)

Mark Puchala II
Mark Puchala II

Reputation: 652

I don't like this, but the fix I ended up using looks like this:

cell = "r"+(j)+cell.substr(2,2);

Since I'm inevitably answering my own question, here, I still want to ask for comments:

How elegant would you say a solution like this is in the long run?

Upvotes: -1

Kijewski
Kijewski

Reputation: 26022

You can use a regular expression: /^r(\d+)c(\d+)/:

var row_col = 'r1c1';
var match = /^r(\d+)c(\d+)/.exec(row_col);  // match string
var row = +match[1];  // extract row
var col = +match[2];  // extract column
// edit row and col as needed
row_col = 'r' + row + 'c' + col;  // "reassemble" string

This will take care of bigger row/column numbers than 9. If that is not to be expected, then read about String.prototype.substring():

var row_col = 'r1c1';
var row = +row_col.substring(1,2);
var col = +row_col.substring(3,4)

Upvotes: 0

Paul
Paul

Reputation: 646

cell.replace(cell[3], i+1) is going to replace the first instance of the '1' character it finds in the string 'r1c1'. In this case it is the '1' at position 1 that gets replaced instead of the '1' at position 3.

To get the results you want, try

var cell = "r1c1";

for (i = 0; i <= 4; i++){
  cell = cell.substring(0, cell.length-1)+(i+1);
}

Upvotes: 5

Related Questions