Skip to content

A platform for community discussion. Free, open, simple.

FIX: Escape regex symbols when replaceText is called for ProseMirror (#32280)

Martin Brennan7a6006f7aa19
diff --git a/app/assets/javascripts/discourse/app/static/prosemirror/lib/text-manipulation.js b/app/assets/javascripts/discourse/app/static/prosemirror/lib/text-manipulation.js
index cefbb2a05f2..d05fffd1045 100644
--- a/app/assets/javascripts/discourse/app/static/prosemirror/lib/text-manipulation.js
+++ b/app/assets/javascripts/discourse/app/static/prosemirror/lib/text-manipulation.js
@@ -7,6 +7,7 @@ import { Slice } from "prosemirror-model";
import { liftListItem, sinkListItem } from "prosemirror-schema-list";
import { TextSelection } from "prosemirror-state";
import { bind } from "discourse/lib/decorators";
+import escapeRegExp from "discourse/lib/escape-regexp";
import { i18n } from "discourse-i18n";
/**
@@ -278,7 +279,7 @@ export default class ProsemirrorTextManipulation {
const markdown = this.convertToMarkdown(this.view.state.doc);
- const regex = opts.regex || new RegExp(oldValue, "g");
+ const regex = opts.regex || new RegExp(escapeRegExp(oldValue), "g");
const index = opts.index || 0;
let matchCount = 0;
diff --git a/app/assets/javascripts/discourse/tests/integration/components/d-editor-test.gjs b/app/assets/javascripts/discourse/tests/integration/components/d-editor-test.gjs
index d87fdba7804..95ca658857b 100644
--- a/app/assets/javascripts/discourse/tests/integration/components/d-editor-test.gjs
+++ b/app/assets/javascripts/discourse/tests/integration/components/d-editor-test.gjs
@@ -1314,3 +1314,35 @@ third line`
}
})();
});
+
+module("Integration | Component | d-editor | rich editor", function (hooks) {
+ setupRenderingTest(hooks);
+
+ test("replaceText escapes markdown symbols that could be regexp symbols", async function (assert) {
+ this.siteSettings.rich_editor = true;
+
+ const initialValue = "Hello\n\n* world\n* am am here $";
+
+ withPluginApi("2.1.0", (api) => {
+ api.onToolbarCreate((toolbar) => {
+ toolbar.addButton({
+ id: "replace-text",
+ icon: "xmark",
+ group: "extras",
+ action: () => {
+ toolbar.context
+ .newToolbarEvent()
+ .replaceText(initialValue, "goodbye");
+ },
+ condition: () => true,
+ });
+ });
+ });
+
+ await render(<template><DEditor @value={{initialValue}} /></template>);
+ await click(".composer-toggle-switch");
+ await click("button.replace-text");
+
+ assert.dom(".ProseMirror p").hasText("goodbye");
+ });
+});