From 1cacf903dcd44bf10af8be920fad4a220fc3b4ad Mon Sep 17 00:00:00 2001 From: Jean Date: Fri, 27 Jun 2025 20:29:04 -0700 Subject: [PATCH] Remake cut feature to be simpler to use and avoid bugs, fixes #35 --- src/replace-words.js | 40 ++++++++++++++++++---------------------- 1 file changed, 18 insertions(+), 22 deletions(-) diff --git a/src/replace-words.js b/src/replace-words.js index 49ae359..c53bdcb 100644 --- a/src/replace-words.js +++ b/src/replace-words.js @@ -230,7 +230,7 @@ function replaceExceptions(options) { /* Replaces cut statements with cuts */ function replaceCuts() { - const searchTerm = /cut\/([^\/]+)\/(-?[\d]+)\/(?:(-?[\d]+)\/)?/i; + const searchTerm = /cut\/([^\/]+)\/(off|only) (first|last) ([1-9][0-9]*)\//i; walk(document.body, searchTerm, null, cutMethod); } @@ -379,31 +379,27 @@ function cutMethod(node, searchTerm, unused) { const match = node.nodeValue.match(searchTerm); if (match == null) { return; } const target = match[1]; - let start = Number(match[2]); - let end = Number(match[3]); + const length = target.length + const isOnly = match[2] == "only"; + const isFirst = match[3] == "first"; + const index = Number(match[4]); - if (isNaN(end)) { - if (start < 0) { // Cut off from the right side - end = target.length + start; + let start, end; + if (isOnly) { + if (isFirst) { // only first n start = 0; - } else { // Cut off from the left side - end = target.length; + end = Math.min(index, length - 1); + } else { // only last n + start = Math.max(length - index, 1); + end = length; } } else { - const isNegStart = (start < 0) || ((start == 0) && (end < 0)); - if (isNegStart) { // Starting from the right, move by end - const mod = start; - start = target.length + mod; - end = target.length + mod + end; - } else { // Starting from the left, move by end - end = start + end; - } - - // Start should always be less than end - if (start > end) { - const greater = start; - start = end; - end = greater; + if (isFirst) { // off first n + start = Math.min(index, length - 1);; + end = length; + } else { // off last n + start = 0; + end = Math.max(length - index, 1); } }