diff --git a/core/block.js b/core/block.js
index d27f5256c..35b2cae62 100644
--- a/core/block.js
+++ b/core/block.js
@@ -1424,16 +1424,19 @@ Blockly.Block.prototype.toString = function(opt_maxLength, opt_emptyToken) {
// Run through our text array and simplify expression to remove parentheses
// around single field blocks.
- for (var i = 2, l = text.length; i < l; i++) {
+ // E.g. ['repeat', '(', '10', ')', 'times', 'do', '?']
+ for (var i = 2; i < text.length; i++) {
if (text[i - 2] == '(' && text[i] == ')') {
text[i - 2] = text[i - 1];
text.splice(i - 1, 2);
- l -= 2;
}
}
- // Join the text array, removing spaces around added paranthesis.
- text = text.join(' ').replace(/(\() | (\))/gmi, '$1$2').trim() || '???';
+ // Join the text array, removing spaces around added parentheses.
+ text = text.reduce(function(acc, value) {
+ return acc + ((acc.substr(-1) == '(' || value == ')') ? '' : ' ') + value;
+ }, '');
+ text = text.trim() || '???';
if (opt_maxLength) {
// TODO: Improve truncation so that text from this block is given priority.
// E.g. "1+2+3+4+5+6+7+8+9=0" should be "...6+7+8+9=0", not "1+2+3+4+5...".
diff --git a/tests/mocha/block_test.js b/tests/mocha/block_test.js
index 34c56ddeb..7995902ce 100644
--- a/tests/mocha/block_test.js
+++ b/tests/mocha/block_test.js
@@ -1710,7 +1710,7 @@ suite('Blocks', function() {
'' +
'' +
'',
- toString: 'repeat 10 times do ?',
+ toString: 'repeat 10 times do ?'
},
{
name: 'nested statement blocks',
@@ -1724,7 +1724,7 @@ suite('Blocks', function() {
'' +
'' +
'',
- toString: 'repeat 10 times do if ? do ?',
+ toString: 'repeat 10 times do if ? do ?'
},
{
name: 'nested Boolean output blocks',
@@ -1740,7 +1740,7 @@ suite('Blocks', function() {
'' +
'' +
'',
- toString: 'if ((? and ?) = ?) do ?',
+ toString: 'if ((? and ?) = ?) do ?'
},
{
name: 'output block',
@@ -1752,7 +1752,7 @@ suite('Blocks', function() {
'' +
'' +
'',
- toString: 'square root 9',
+ toString: 'square root 9'
},
{
name: 'nested Number output blocks',
@@ -1782,7 +1782,7 @@ suite('Blocks', function() {
'' +
'' +
'',
- toString: '(10 × 5) + 3',
+ toString: '(10 × 5) + 3'
},
{
name: 'nested String output blocks',
@@ -1799,8 +1799,15 @@ suite('Blocks', function() {
'' +
'' +
'',
- toString: 'create text with “ Hello ” “ World ”',
+ toString: 'create text with “ Hello ” “ World ”'
},
+ {
+ name: 'parentheses in string literal',
+ xml: '' +
+ 'foo ( bar ) baz' +
+ '',
+ toString: '“ foo ( bar ) baz ”'
+ }
];
// Create mocha test cases for each toString test.
toStringTests.forEach(function(t) {