在单个单词内插入文本.独特的环境

Insert text inside of a single word. Unique circumstance

本文关键字:环境 插入文本 单个单      更新时间:2023-09-26

我有一个非常奇怪的开箱即用的问题,但有充分的理由。

如果我有一个变量,例如:

var myText = "Select an option, and we'll update you.";

我需要将其更改为:

"Se~lect an option, and we'll up~date you.";

现在这个符号无关紧要了。我只需要为数据库相关的单词使用任何类型的特殊字符。选择、更新、计数等。但我也想选择一个典型的人在打字时不经常使用的字符。

我希望有一种方法可以将这些字符插入到指定单词的列表中,如果它们存在于变量中的话。

流程:

用户以val()捕获在变量中的形式输入注释。然后取变量并在这些单词中插入一个特殊字符。

在SQL级别上,在将这些字符插入数据库之前,我会使用替换来解析这些字符。

非常感谢。。。

也许这样的东西应该给你一个开始(如果你真的必须的话)。

Javascript

var words = ["select", "update", "count"];
function modify(text) {
    words.forEach(function (word) {
        text = text.replace(new RegExp("''b" + word + "''b", "gi"), function(match) {
            var insertAt = Math.floor(match.length / 2);
            return match.slice(0, insertAt) + "~" + match.slice(insertAt);
        });
    });
    return text;
}
console.log(modify("Select an option, and we'll update you. Count. Select an option, and we'll update you."));

输出

Sel~ect an option, and we'll upd~ate you. Co~unt. Sel~ect an option, and we'll upd~ate you.

jsfidd

更新:优化

Javascript

var words = ["select", "update", "count"],
    regexs = words.map(function (word) {
        return new RegExp("''b" + word + "''b", "gi");
    });
function modify(text) {
    regexs.forEach(function (regex) {
        text = text.replace(regex, function (match) {
            var insertAt = Math.floor(match.length / 2);
            return match.slice(0, insertAt) + "~" + match.slice(insertAt);
        });
    });
    return text;
}
console.log(modify("Select an option, and we'll update you. Count. Select an option, and we'll update you."));

jsfidd

如果绝对不能解决这个问题,可以将注释编码为JSON,并用其unicode转义序列表示每个字符:

function unicode_stringify(s) {
    var result = [];
    for (var i = 0; i < s.length; i++) {
        result.push('''u' + ('0000' + s.charCodeAt(i).toString(16)).slice(-4));
    }
    return '"' + result.join('') + '"';
}

在你的服务器上解码它,它应该可以正常工作:

> unicode_stringify('SELECT * FROM comments')
""'u0053'u0045'u004c'u0045'u0043'u0054'u0020'u002a'u0020'u0046'u0052'u004f'u004d'u0020'u0063'u006f'u006d'u006d'u0065'u006e'u0074'u0073""
> JSON.parse(unicode_stringify('SELECT * FROM comments'))
"SELECT * FROM comments"

请仅在万不得已的情况下使用。