Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

代码块里面的文本不应该被错误转义 #1035

Closed
terwer opened this issue Feb 18, 2024 · 0 comments
Closed

代码块里面的文本不应该被错误转义 #1035

terwer opened this issue Feb 18, 2024 · 0 comments
Labels
bug Something isn't working

Comments

@terwer
Copy link
Owner

terwer commented Feb 18, 2024

==>  Preparing: select * from user where id=?
==> Parameters: 1(Integer)
<==    Columns: id, username
<==        Row: 1, tyw
<==      Total: 1
User{id=1, username='tyw'}

解决

function replaceMarks(md) {
    // 匹配代码块
    let codeBlockRegex = /```[\s\S]*?```/g;

    // 将代码块替换为占位符,避免在后续处理中受到影响
    let placeholders = [];
    md = md.replace(codeBlockRegex, function(match) {
        let placeholder = `CODE_BLOCK_${placeholders.length}`;
        placeholders.push(match);
        return placeholder;
    });

    // 匹配行内代码块
    let inlineCodeRegex = /`[^`]*`/g;
    let inlineCodePlaceholders = [];
    md = md.replace(inlineCodeRegex, function(match) {
        let placeholder = `INLINE_CODE_${inlineCodePlaceholders.length}`;
        inlineCodePlaceholders.push(match);
        return placeholder;
    });

    // 正则表达式,匹配严格符合 == 开始和结束的部分,但不在代码块和行内代码块内
    let regex = /(?<!`|```)==([^=]+)==(?!.*(?:`|```))(?!.*INLINE_CODE_\d+)/g;

    // 替换非代码块和行内代码块内的 == 部分
    md = md.replace(regex, '<span style="font-weight: bold;" class="mark">$1</span>');

    // 将代码块恢复回去
    for (let i = 0; i < placeholders.length; i++) {
        md = md.replace(`CODE_BLOCK_${i}`, placeholders[i]);
    }

    // 将行内代码块恢复回去
    for (let i = 0; i < inlineCodePlaceholders.length; i++) {
        md = md.replace(`INLINE_CODE_${i}`, inlineCodePlaceholders[i]);
    }

    return md;
}

// 测试函数
let md = `
==This should be bold==

\`\`\`javascript
// This is a code block
let x = 10;
console.log(x);
\`\`\`

This is an `inline code block`.

==This should also be bold==
`;

let processedMd = replaceMarks(md);
console.log(processedMd);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

1 participant