Skip to content

Commit f6daf8d

Browse files
committed
Fix bug where replacing went incorrectly
1 parent 5ae6df4 commit f6daf8d

File tree

2 files changed

+45
-7
lines changed

2 files changed

+45
-7
lines changed

index.js

+4-7
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,9 @@ function findAndReplace(tree, find, replace, options) {
3434

3535
return handler;
3636

37-
function handler(node, pos, parent) {
37+
function handler(node, parent) {
3838
var siblings = parent.children;
39+
var pos = siblings.indexOf(node);
3940
var value = node.value;
4041
var find = pair[0];
4142
var replace = pair[1];
@@ -102,12 +103,10 @@ function findAndReplace(tree, find, replace, options) {
102103
node = nodes[index];
103104

104105
if (node.type === 'text') {
105-
subhandler(node, pos, parent);
106+
subhandler(node, parent);
106107
} else {
107108
search(node, settings, subhandler);
108109
}
109-
110-
pos++;
111110
}
112111
}
113112
}
@@ -124,16 +123,14 @@ function search(tree, options, handler) {
124123
function visitor(node, parents) {
125124
var length = parents.length;
126125
var index = length;
127-
var parent;
128126

129127
while (index--) {
130128
if (is(parents[index], ignore)) {
131129
return;
132130
}
133131
}
134132

135-
parent = parents[length - 1];
136-
handler(node, parent.children.indexOf(node), parent);
133+
handler(node, parents[length - 1]);
137134
}
138135
}
139136

test.js

+41
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,47 @@ test('findAndReplace', function (t) {
158158
'should ignore from options'
159159
);
160160

161+
t.deepEqual(
162+
findAndReplace(h('p', 'Some emphasis, importance, and code.'), {
163+
importance: function (match) {
164+
return h('strong', match);
165+
},
166+
code: function (match) {
167+
return h('code', match);
168+
},
169+
emphasis: function (match) {
170+
return h('em', match);
171+
}
172+
}),
173+
create(),
174+
'should not be order-sensitive with strings'
175+
);
176+
177+
t.deepEqual(
178+
findAndReplace(h('p', 'Some emphasis, importance, and code.'), [
179+
[
180+
/importance/g,
181+
function (match) {
182+
return h('strong', match);
183+
}
184+
],
185+
[
186+
/code/g,
187+
function (match) {
188+
return h('code', match);
189+
}
190+
],
191+
[
192+
/emphasis/g,
193+
function (match) {
194+
return h('em', match);
195+
}
196+
]
197+
]),
198+
create(),
199+
'should not be order-sensitive with regexes'
200+
);
201+
161202
t.end();
162203
});
163204

0 commit comments

Comments
 (0)