gpt4 book ai didi

javascript - 如何提高 JavaScript 文本格式化程序的性能?

转载 作者:行者123 更新时间:2023-11-30 13:30:37 26 4
gpt4 key购买 nike

我允许我的用户用“*”、“/”、“_”和“-”将单词括起来,作为一种简写方式,表示他们希望将文本加粗、斜体、下划线或删除线。不幸的是,当页面充满使用此标记的文本时,我发现速度明显下降(可接受的边界)。

这是我为处理此任务而编写的 JavaScript。您能否提供有关我如何加快速度的反馈?

function handleContentFormatting(content) {
content = handleLineBreaks(content);

var bold_object = {'regex': /\*(.|\n)+?\*/i, 'open': '<b>', 'close': '</b>'};
var italic_object = {'regex': /\/(?!\D>|>)(.|\n)+?\//i, 'open': '<i>', 'close': '</i>'};
var underline_object = {'regex': /\_(.|\n)+?\_/i, 'open': '<u>', 'close': '</u>'};
var strikethrough_object = {'regex': /\-(.|\n)+?\-/i, 'open': '<del>', 'close': '</del>'};

var format_objects = [bold_object, italic_object, underline_object, strikethrough_object];

for( obj in format_objects ) {
content = handleTextFormatIndicators(content, format_objects[obj]);
}

return content;
}

//@param obj --- an object with 3 properties:
// 1.) the regex to search with
// 2.) the opening HTML tag that will replace the opening format indicator
// 3.) the closing HTML tag that will replace the closing format indicator
function handleTextFormatIndicators(content, obj) {
while(content.search(obj.regex) > -1) {
var matches = content.match(obj.regex);
if( matches && matches.length > 0) {
var new_segment = obj.open + matches[0].slice(1,matches[0].length-1) + obj.close;
content = content.replace(matches[0],new_segment);
}
}
return content;
}

最佳答案

  1. 使用标志 /ig 更改您的正则表达式并删除 while 循环。

  2. 用普通的 for 循环更改您的 for(obj in format_objects) 循环,因为 format_objects 是一个数组。


更新

好的,我花时间根据您的代码编写了一个更快、更简单的解决方案:

function handleContentFormatting(content) {
content = handleLineBreaks(content);

var bold_object = {'regex': /\*([^*]+)\*/ig, 'replace': '<b>$1</b>'},
italic_object = {'regex': /\/(?!\D>|>)([^\/]+)\//ig, 'replace': '<i>$1</i>'},
underline_object = {'regex': /\_([^_]+)\_/ig, 'replace': '<u>$1</u>'},
strikethrough_object = {'regex': /\-([^-]+)\-/ig, 'replace': '<del>$1</del>'};

var format_objects = [bold_object, italic_object, underline_object, strikethrough_object],
i = 0, foObjSize = format_objects.length;

for( i; i < foObjSize; i++ ) {
content = handleTextFormatIndicators(content, format_objects[i]);
}

return content;
}

//@param obj --- an object with 2 properties:
// 1.) the regex to search with
// 2.) the replace string
function handleTextFormatIndicators(content, obj) {
return content.replace(obj.regex, obj.replace);
}

Here is a demo .

这将适用于嵌套和/或非嵌套格式边界。如果愿意,您可以完全省略函数 handleTextFormatIndicators,并在 handleContentFormatting 内进行内联替换。

关于javascript - 如何提高 JavaScript 文本格式化程序的性能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6902577/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com