From 2586a871e1fd48e6bf34137d01b6fc936cdbeb9f Mon Sep 17 00:00:00 2001 From: Trevor Buckner Date: Thu, 2 Dec 2021 11:45:10 -0500 Subject: [PATCH] Use capture groups, add default "alt text" if none selected Also allow whitespace at end and start of selection, so you don't have to be perfect. --- shared/naturalcrit/codeEditor/codeEditor.jsx | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/shared/naturalcrit/codeEditor/codeEditor.jsx b/shared/naturalcrit/codeEditor/codeEditor.jsx index 495166c1b..b7bb8b435 100644 --- a/shared/naturalcrit/codeEditor/codeEditor.jsx +++ b/shared/naturalcrit/codeEditor/codeEditor.jsx @@ -156,16 +156,17 @@ const CodeEditor = createClass({ }, makeLink : function() { - const isLink = /^\[(.*)(\]\()(.*)\)$/g; - const selection = this.codeMirror.getSelection(); - if(isLink.test(selection) == true){ - const altText = selection.slice(1, selection.lastIndexOf('](')); // could likely be done better with capture groups - const url = selection.slice(selection.lastIndexOf('](') + 2, -1); // could likely be done better with capture groups + const isLink = /^\[(.*)\]\((.*)\)$/; + const selection = this.codeMirror.getSelection().trim(); + let match; + if(match = isLink.exec(selection)){ + const altText = match[1]; + const url = match[2]; this.codeMirror.replaceSelection(`${altText} ${url}`); const cursor = this.codeMirror.getCursor(); this.codeMirror.setSelection({ line: cursor.line, ch: cursor.ch - url.length }, { line: cursor.line, ch: cursor.ch }); } else { - this.codeMirror.replaceSelection(`[${selection}](url)`); + this.codeMirror.replaceSelection(`[${selection || 'alt text'}](url)`); const cursor = this.codeMirror.getCursor(); this.codeMirror.setSelection({ line: cursor.line, ch: cursor.ch - 4 }, { line: cursor.line, ch: cursor.ch - 1 }); }