5

The code (a simple replace loop):

fs.readFile(filename, 'utf8', function(err, data) {
  if (err) throw err

  data = data.split('\n\n')
  var tree = data

  for (var i = 0; i < tree.length; ++i) {
    if (tree[i].match(/^#/g)) {
      data[i] = data[i]
        .replace(/^#### (.*)/gm, '<h4>$1</h4>')
        .replace(/^### (.*)/gm, '<h3>$1</h3>')
        .replace(/^## (.*)/gm, '<h2>$1</h2>')
        .replace(/^# (.*)/gm, '<h1>$1</h1>')
    }
  }

  data = data.join('\n\n')
  tree = tree.join('\n\n')

  console.log(data)
  console.log(tree)

So in this case both data and tree have the same output:

<h1>Test</h1>

<h2>Test</h2>

Lorem "**ipsum?**" dolor 'sit!' amet

Anooo

* * *

"Ipsum?" "'**dolor**'" *sit!* amet, consetetur
eirmod tempor--invidunt **ut** labore

Anothes

What I want to do is to preserve the original value of data in tree so that only data changes but not tree.

How to do that?

tree should remain like this:

# Test

## Test

Lorem "**ipsum?**" dolor 'sit!' amet

Anooo

* * *

"Ipsum?" "'**dolor**'" *sit!* amet, consetetur
eirmod tempor--invidunt **ut** labore

Anothes
alexchenco
  • 53,565
  • 76
  • 241
  • 413

3 Answers3

5

Use Array.prototype.slice().

The slice() method returns a shallow copy of a portion of an array into a new array object.

var tree = data.slice();

Rodrigo Siqueira
  • 1,164
  • 8
  • 20
3

Use a hack

var tree = data.slice(0)

It may be wrapped to a separate function/method.

phts
  • 3,889
  • 1
  • 19
  • 31
2

Jquery

var newObj = obj.extend({}, obj)

AngularJS

var newObj = angular.copy(obj)

Plain javascript

JSON.parse(JSON.stringify(obj));
Asher
  • 393
  • 3
  • 16