Once again, I try to understand why SSJS in SFMC is acting differently compared to JS.
Based on the following sample: RegExp.prototype.exec()
SSJS Example:
<script runat=server>
var str = 'table football, foosball';
var test = [
/foo*/g,
new RegExp(/foo*/g),
new RegExp(/foo*/, 'g'),
new RegExp('foo*', 'g')
];
for (var i = 0; i < test.length; i++) {
Platform.Response.Write(i + ': ' + Platform.Function.Stringify(test[i].exec(str)) + '<br/>');
}
</script>
Output:
0: ["foo", null, null]
1: null
2: null
3: ["foo", null, null]
This is wrong based on what we normally would expect from RegExp.exec()
JS sample:
var str = 'table football, foosball';
var test = [
/foo*/g,
new RegExp(/foo*/g),
new RegExp(/foo*/, 'g'),
new RegExp('foo*', 'g')
];
for (var i = 0; i < test.length; i++) {
console.log(i + ':' + test[i].exec(str));
}
Output:
> "0:foo"
> "1:foo"
> "2:foo"
> "3:foo"
As RegExp
is stateful
we should be able to do the following:
JS
var reg = /foo*/g;
var str = 'table football, foosball';
console.log(reg.exec(str))
console.log(reg.exec(str))
console.log(reg.exec(str))
Output
> Array ["foo"]
> Array ["foo"]
> null
This is as expected because each call of exec
will be starting on the lastIndex
due to its stateful nature.
SSJS
<script runat=server>
var str = 'table football, foosball';
var reg = /foo*/g;
Platform.Response.Write(Platform.Function.Stringify(reg.exec(str)) + '<br/>');
Platform.Response.Write(Platform.Function.Stringify(reg.exec(str)) + '<br/>');
Platform.Response.Write(Platform.Function.Stringify(reg.exec(str)) + '<br/>');
</script>
Output
["foo", null, null]
["foo", null, null]
["foo", null, null]
Question:
What am I missing here? Why is SSJS RegExp.exec()
acting so different? How can I get the same result as from JS?