diff --git a/src/com/google/javascript/jscomp/PeepholeReplaceKnownMethods.java b/src/com/google/javascript/jscomp/PeepholeReplaceKnownMethods.java index 4223334231a..2faaee6030b 100644 --- a/src/com/google/javascript/jscomp/PeepholeReplaceKnownMethods.java +++ b/src/com/google/javascript/jscomp/PeepholeReplaceKnownMethods.java @@ -218,6 +218,8 @@ private Node tryFoldKnownStringMethods(Node subtree, Node callTarget) { return tryFoldStringToLowerCase(subtree, stringNode); case "toUpperCase": return tryFoldStringToUpperCase(subtree, stringNode); + case "trim": + return tryFoldStringTrim(subtree, stringNode); default: // fall out } } else { @@ -319,6 +321,20 @@ private Node tryFoldStringToUpperCase(Node subtree, Node stringNode) { return replacement; } + /** + * @return The trimmed string Node. + */ + private Node tryFoldStringTrim(Node subtree, Node stringNode) { + // See ECMA 15.5.4.20, 7.2, and 7.3 + // All Unicode 10.0 whitespace + BOM + String whitespace = "[ \t\n-\r\\u0085\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000\\uFEFF]+"; + String trimmed = stringNode.getString().replaceAll("^" + whitespace + "|" + whitespace + "$", ""); + Node replacement = IR.string(trimmed); + subtree.replaceWith(replacement); + compiler.reportChangeToEnclosingScope(replacement); + return replacement; + } + /** * @param input string representation of a number * @return string with leading and trailing zeros removed diff --git a/test/com/google/javascript/jscomp/PeepholeIntegrationTest.java b/test/com/google/javascript/jscomp/PeepholeIntegrationTest.java index 1f0aad96db0..733e743e7d5 100644 --- a/test/com/google/javascript/jscomp/PeepholeIntegrationTest.java +++ b/test/com/google/javascript/jscomp/PeepholeIntegrationTest.java @@ -377,6 +377,7 @@ public void testTemplateStringsKnownMethods() { test("x = `abcdef`.charCodeAt(0)", "x = 97"); test("x = `abc`.toUpperCase()", "x = 'ABC'"); test("x = `ABC`.toLowerCase()", "x = 'abc'"); + test("x = `\t\n\uFEFF\t asd foo bar \r\n`.trim()", "x = 'asd foo bar'"); test("x = parseInt(`123`)", "x = 123"); test("x = parseFloat(`1.23`)", "x = 1.23"); }