Javascript - 查找和替换某些字符的问题

问题描述 投票:0回答:1

我将以下 HTML 片段存储在变量中,我正在尝试查找并替换某些字符,以便它将与我正在使用的模板对齐,该模板在进行必要的更改后将代码转换为组件.

我需要更新以下内容,这是所需内容的示例:

    let testall = `<div class="row"><span>Lorem Ipsum is simply dummy text of the printing and 
    typesetting industry. <u><a href="test/test_url/">dummy text</a></u></span><span 
    id="extra">Lorem Ipsum has been the industry's standard dummy text ever since the 1500's when 
    an unknown printer took a galley of type and scrambled it to make a type specimen book. It has 
    survived not only five centuries</span></div>`

    // this replace works
    console.log("Test 1: " + testall.replaceAll("'","&apos;"));

    // this replace doesn't fully work as it doesn't include the backslash after
    console.log("Test 2: " + testall.replaceAll('<a href="','<a href=\"{{store}}'));

    // this replace doesn't work - i tried an alternative below, however at adds 2 backslashes instead of only one
    console.log("Test 3: " + testall.replaceAll("</","<\/"));
    
    // alternative - tried on span tag - adds 2 backslashes instead of only one
    console.log("Test 4: " + testall.replaceAll(/<\/span>/g, '<\\/span>'));

从上面可以看出,第一个查找和替换有效,但是,当我替换/添加反斜杠时,我遇到了麻烦。

任何帮助都会很棒。

javascript regex replace find
1个回答
0
投票

看起来您正在处理 HTML 字符串中的转义字符。在处理涉及特殊字符的字符串替换时,正确转义它们非常重要。在 JavaScript 中,您可以使用双反斜杠 (\) 来表示正则表达式中的单个反斜杠。

让我们更新您的代码来解决这些问题:

    let testall = `<div class="row"><span>Lorem Ipsum is simply dummy text of the printing and 
typesetting industry. <u><a href="test/test_url/">dummy text</a></u></span><span 
id="extra">Lorem Ipsum has been the industry's standard dummy text ever since the 1500's when 
an unknown printer took a galley of type and scrambled it to make a type specimen book. It has 
survived not only five centuries</span></div>`;

// Replace single quotes with &apos;
console.log("Test 1: " + testall.replaceAll("'", "&apos;"));

// Replace <a href=" with <a href="{{store}}
console.log("Test 2: " + testall.replaceAll('<a href="', '<a href="{{store}}'));

// Replace </ with <\/
console.log("Test 3: " + testall.replaceAll("</", "<\\/"));

// Alternative: Use a regular expression with double backslashes
console.log("Test 4: " + testall.replaceAll(/<\/span>/g, '<\\/span>'));

测试3和测试4中,关键是使用双反斜杠来转义反斜杠。这确保了反斜杠在替换中被视为文字字符。

这应该可以解决您在替换反斜杠时遇到的问题。

© www.soinside.com 2019 - 2024. All rights reserved.