Skip to content

Commit

Permalink
fix: escape backslash in the middle of sentence (#2588)
Browse files Browse the repository at this point in the history
* test: add test for escape baskslash

* fix: escape backslash in the middle of sentence
  • Loading branch information
jajugoguma authored Jul 5, 2022
1 parent 66db3f8 commit 3fc8ac5
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 6 deletions.
11 changes: 11 additions & 0 deletions apps/editor/src/__test__/unit/convertor.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1098,4 +1098,15 @@ describe('Convertor', () => {

expect(result).toBe(`<strong>"test"</strong>a`);
});

it('should escape the backslash, which is a plain chracter in the middle of a sentence', () => {
const markdown = source`
backslash \\in the middle of a sentence
`;
const expected = source`
backslash \\\\in the middle of a sentence
`;

assertConverting(markdown, expected);
});
});
18 changes: 12 additions & 6 deletions apps/editor/src/utils/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ const reEscapeHTML = /<([a-zA-Z_][a-zA-Z0-9\-._]*)(\s|[^\\>])*\/?>|<(\/)([a-zA-Z
const reEscapeBackSlash = /\\[!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~\\]/g;
const reEscapePairedChars = /[*_~`]/g;
const reMdImageSyntax = /!\[.*\]\(.*\)/g;
const reEscapedCharInLinkSyntax = /[[\]]/g; //
const reEscapedCharInLinkSyntax = /[[\]]/g;
const reEscapeBackSlashInSentence = /(?:^|[^\\])\\(?!\\)/g;

const XMLSPECIAL = '[&<>"]';
const reXmlSpecial = new RegExp(XMLSPECIAL, 'g');
Expand Down Expand Up @@ -118,22 +119,27 @@ export function escapeTextForLink(text: string) {
}

export function escape(text: string) {
const replacer = (matched: string) => `\\${matched}`;
const aheadReplacer = (matched: string) => `\\${matched}`;
const behindReplacer = (matched: string) => `${matched}\\`;

let escapedText = text.replace(reSpaceMoreThanOne, ' ');

if (reEscapeBackSlash.test(escapedText)) {
escapedText = escapedText.replace(reEscapeBackSlash, replacer);
escapedText = escapedText.replace(reEscapeBackSlash, aheadReplacer);
}

escapedText = escapedText.replace(reEscapePairedChars, replacer);
if (reEscapeBackSlashInSentence.test(escapedText)) {
escapedText = escapedText.replace(reEscapeBackSlashInSentence, behindReplacer);
}

escapedText = escapedText.replace(reEscapePairedChars, aheadReplacer);

if (reEscapeHTML.test(escapedText)) {
escapedText = escapedText.replace(reEscapeHTML, replacer);
escapedText = escapedText.replace(reEscapeHTML, aheadReplacer);
}

if (isNeedEscapeText(escapedText)) {
escapedText = escapedText.replace(reEscapeChars, replacer);
escapedText = escapedText.replace(reEscapeChars, aheadReplacer);
}

return escapedText;
Expand Down

0 comments on commit 3fc8ac5

Please sign in to comment.