草庐IT

javascript - 文本替换后匹配子字符串的光标位置

coder 2025-01-15 原文

<分区>

长话短说

我有替换文本、字符串和光标位置(一个数字)的函数,如果字符串的长度发生变化,我需要为使用替换函数创建的新字符串获取更正的位置(一个数字):

input and cursor position:  foo ba|r text
replacement: foo -> baz_text, bar -> quux_text
result: baz_text qu|ux_text text

input and cursor position:  foo bar| text
replacement: foo -> baz_text, bar -> quux_text
result: baz_text quux_text| text

input and cursor position:  foo bar| text
replacement: foo -> f, bar -> b
result: f b| text

input and cursor position:  foo b|ar text
replacement: foo -> f, bar -> b
result: f b| text

问题是我可以在原始文本上使用子字符串,但替换将无法匹配整个单词,因此需要对整个文本进行替换,但子字符串将无法匹配替换。

当原始光标位于被替换单词的中间时,光标始终位于单词末尾的解决方案也很好。

现在是我的实现,在 jQuery 终端中我有一组格式化程序函数:

$.terminal.defaults.formatters

他们接受一个字符串并且它应该返回新的字符串它工作正常除了这种情况:

当我有如果打破命令行会改变长度的格式化程序时,例如这个格式化程序:

$.terminal.defaults.formatters.push(function(string) {
   return string.replace(/:smile:/g, 'a')
                .replace(/(foo|bar|baz)/g, 'text_$1');
});

然后命令行获取新字符串时光标位置错误。

我已经尝试解决这个问题,但它没有按预期工作,终端的内部看起来像这样,

当我更改 position 时,我创建了另一个变量 formatted_position,它在命令行中用于显示光标。为了获得这个值(value),我使用了这个:

formatted_position = position;
var string = formatting(command);
var len = $.terminal.length(string);
var command_len = $.terminal.length(command);
if (len !== command_len) {
    var orig_sub = $.terminal.substring(command, 0, position);
    var orig_len = $.terminal.length(orig_sub);
    var formatted = formatting(orig_sub);
    var formatted_len = $.terminal.length(formatted);
    if (orig_len > formatted_len) {
        // if formatting make substring - (text before cursor)
        // shorter then subtract the difference
        formatted_position -= orig_len - formatted_len;
    } else if (orig_len < formatted_len) {
        // if the formatted string is longer add difference
        formatted_position += formatted_len - orig_len;
    }
}

if (formatted_position > len) {
    formatted_position = len;
} else if (formatted_position < 0) {
    formatted_position = 0;
}

$.terminal.substring 和 $.terminal.length 是终端格式感知的辅助函数(文本看起来像这样 [[b;#fff;]hello])如果你会写您可以使用普通文本并使用字符串方法的解决方案。

问题是当我将光标移动到被更改的单词的中间时

当文本较长时,它有点工作,但对于较短的字符串,当文本位于被替换的单词的中间时,光标会跳到右边。

我也尝试使用以下代码修复此问题:

function find_diff(callback) {
    var start = position === 0 ? 0 : position - 1;
    for (var i = start; i < command_len; ++i) {
        var substr = $.terminal.substring(command, 0, i);
        var next_substr = $.terminal.substring(command, 0, i + 1);
        var formatted = formatting(next_substr);
        var substr_len = $.terminal.length(substr);
        var formatted_len = $.terminal.length(formatted);
        var diff = Math.abs(substr_len - formatted_len);
        if (diff > 1) {
            return diff;
        }
    }
    return 0;
}

...

} else if (len < command_len) {
    formatted_position -= find_diff();
} else if (len > command_len) {
    formatted_position += find_diff();
}

但我认为这会使情况变得更糟,因为当光标位于替换词之前或中间时它会发现差异,并且只有当光标位于替换词的中间时它才会发现差异。

你可以在这个codepen中看到我尝试的结果https://codepen.io/jcubic/pen/qPVMPg?editors=0110 (允许输入表情符号和 foo bar baz 被替换为 text_$1)

更新:

我已经用这段代码让它工作了:

    // ---------------------------------------------------------------------
    // :: functions used to calculate position of cursor when formatting
    // :: change length of output text like with emoji demo
    // ---------------------------------------------------------------------
    function split(formatted, normal) {
        function longer(str) {
            return found && length(str) > length(found) || !found;
        }
        var formatted_len = $.terminal.length(formatted);
        var normal_len = $.terminal.length(normal);
        var found;
        for (var i = normal_len; i > 1; i--) {
            var test_normal = $.terminal.substring(normal, 0, i);
            var formatted_normal = formatting(test_normal);
            for (var j = formatted_len; j > 1; j--) {
                var test_formatted = $.terminal.substring(formatted, 0, j);
                if (test_formatted === formatted_normal &&
                    longer(test_normal)) {
                    found = test_normal;
                }
            }
        }
        return found || '';
    }
    // ---------------------------------------------------------------------
    // :: return index after next word that got replaced by formatting
    // :: and change length of text
    // ---------------------------------------------------------------------
    function index_after_formatting(position) {
        var start = position === 0 ? 0 : position - 1;
        var command_len = $.terminal.length(command);
        for (var i = start; i < command_len; ++i) {
            var substr = $.terminal.substring(command, 0, i);
            var next_substr = $.terminal.substring(command, 0, i + 1);
            var formatted_substr = formatting(substr);
            var formatted_next = formatting(next_substr);
            var substr_len = length(formatted_substr);
            var next_len = length(formatted_next);
            var test_diff = Math.abs(next_len - substr_len);
            if (test_diff > 1) {
                return i;
            }
        }
    }
    // ---------------------------------------------------------------------
    // :: main function that return corrected cursor position on display
    // :: if cursor is in the middle of the word that is shorter the before
    // :: applying formatting then the corrected position is after the word
    // :: so it stay in place when you move real cursor in the middle
    // :: of the word
    // ---------------------------------------------------------------------
    function get_formatted_position(position) {
        var formatted_position = position;
        var string = formatting(command);
        var len = $.terminal.length(string);
        var command_len = $.terminal.length(command);
        if (len !== command_len) {
            var orig_sub = $.terminal.substring(command, 0, position);
            var orig_len = $.terminal.length(orig_sub);
            var sub = formatting(orig_sub);
            var sub_len = $.terminal.length(sub);
            var diff = Math.abs(orig_len - sub_len);
            if (false && orig_len > sub_len) {
                formatted_position -= diff;
            } else if (false && orig_len < sub_len) {
                formatted_position += diff;
            } else {
                var index = index_after_formatting(position);
                var to_end = $.terminal.substring(command, 0, index + 1);
                //formatted_position -= length(to_end) - orig_len;
                formatted_position -= orig_len - sub_len;
                if (orig_sub && orig_sub !== to_end) {
                    var formatted_to_end = formatting(to_end);
                    var common = split(formatted_to_end, orig_sub);
                    var re = new RegExp('^' + $.terminal.escape_regex(common));
                    var to_end_rest = to_end.replace(re, '');
                    var to_end_rest_len = length(formatting(to_end_rest));
                    if (common orig_sub !== common) {
                        var commnon_len = length(formatting(common));
                        formatted_position = commnon_len + to_end_rest_len;
                    }
                }
            }
            if (formatted_position > len) {
                formatted_position = len;
            } else if (formatted_position < 0) {
                formatted_position = 0;
            }
        }
        return formatted_position;
    }

当您输入表情符号作为第一个字符并且光标位于 :smile: 单词的中间时,它不适用于一种情况。如何修复 get_formatted_position 函数以在替换后具有正确的固定位置?

更新:我提出了不同且简单的问题,并使用接受正则表达式和字符串的 trackingReplace 函数获得了解决方案,因此我更改了格式化程序的 API 以接受带有正则表达式和字符串的数组函数Correct substring position after replacement

有关javascript - 文本替换后匹配子字符串的光标位置的更多相关文章

  1. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  2. Ruby 解析字符串 - 2

    我有一个字符串input="maybe(thisis|thatwas)some((nice|ugly)(day|night)|(strange(weather|time)))"Ruby中解析该字符串的最佳方法是什么?我的意思是脚本应该能够像这样构建句子:maybethisissomeuglynightmaybethatwassomenicenightmaybethiswassomestrangetime等等,你明白了......我应该一个字符一个字符地读取字符串并构建一个带有堆栈的状态机来存储括号值以供以后计算,还是有更好的方法?也许为此目的准备了一个开箱即用的库?

  3. ruby-on-rails - 在 Rails 中将文件大小字符串转换为等效千字节 - 2

    我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,

  4. ruby-on-rails - unicode 字符串的长度 - 2

    在我的Rails(2.3,Ruby1.8.7)应用程序中,我需要将字符串截断到一定长度。该字符串是unicode,在控制台中运行测试时,例如'א'.length,我意识到返回了双倍长度。我想要一个与编码无关的长度,以便对unicode字符串或latin1编码字符串进行相同的截断。我已经了解了Ruby的大部分unicode资料,但仍然有些一头雾水。应该如何解决这个问题? 最佳答案 Rails有一个返回多字节字符的mb_chars方法。试试unicode_string.mb_chars.slice(0,50)

  5. ruby - 将差异补丁应用于字符串/文件 - 2

    对于具有离线功能的智能手机应用程序,我正在为Xml文件创建单向文本同步。我希望我的服务器将增量/差异(例如GNU差异补丁)发送到目标设备。这是计划:Time=0Server:hasversion_1ofXmlfile(~800kiB)Client:hasversion_1ofXmlfile(~800kiB)Time=1Server:hasversion_1andversion_2ofXmlfile(each~800kiB)computesdeltaoftheseversions(=patch)(~10kiB)sendspatchtoClient(~10kiBtransferred)Cl

  6. ruby - 使用 ruby​​ 将 HTML 转换为纯文本并维护结构/格式 - 2

    我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h

  7. ruby-on-rails - Rails 常用字符串(用于通知和错误信息等) - 2

    大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje

  8. ruby - 如何以所有可能的方式将字符串拆分为长度最多为 3 的连续子字符串? - 2

    我试图获取一个长度在1到10之间的字符串,并输出将字符串分解为大小为1、2或3的连续子字符串的所有可能方式。例如:输入:123456将整数分割成单个字符,然后继续查找组合。该代码将返回以下所有数组。[1,2,3,4,5,6][12,3,4,5,6][1,23,4,5,6][1,2,34,5,6][1,2,3,45,6][1,2,3,4,56][12,34,5,6][12,3,45,6][12,3,4,56][1,23,45,6][1,2,34,56][1,23,4,56][12,34,56][123,4,5,6][1,234,5,6][1,2,345,6][1,2,3,456][123

  9. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  10. ruby - 如何使用文字标量样式在 YAML 中转储字符串? - 2

    我有一大串格式化数据(例如JSON),我想使用Psychinruby​​同时保留格式转储到YAML。基本上,我希望JSON使用literalstyle出现在YAML中:---json:|{"page":1,"results":["item","another"],"total_pages":0}但是,当我使用YAML.dump时,它不使用文字样式。我得到这样的东西:---json:!"{\n\"page\":1,\n\"results\":[\n\"item\",\"another\"\n],\n\"total_pages\":0\n}\n"我如何告诉Psych以想要的样式转储标量?解

随机推荐