在单个单词内插入文本.独特的环境
Insert text inside of a single word. Unique circumstance
我有一个非常奇怪的开箱即用的问题,但有充分的理由。
如果我有一个变量,例如:
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"
请仅在万不得已的情况下使用。
相关文章:
- 我可以在网页正文中插入文本链接吗
- 使用.format在一些HTML代码中插入文本,会出现错误(Python)
- JavaScript 在文本区域中的特定位置插入文本
- CKEditor - 插入文本在 setData 之后不起作用
- 在两个括号内插入文本 - Javascript
- 将值插入文本区域可以绕过所需的检查
- Applescript运行Javascript,并在提示中插入文本
- 如何在Web SQL数据库中逐行插入文本文件
- 如何在Wysihtml5沙盒编辑器中的光标位置插入文本
- 如果在 IE 中最后附加光标,则在光标位置的文本区域中插入文本
- 是否可以在文本区域中插入文本并更新撤消/重做队列
- Javascript:在指定行插入文本
- 在文本字段中插入文本后聚焦光标
- 使用 Greasemonkey 在现有元素之前插入文本节点时出现问题
- 在当前卡雷位置插入文本不起作用(多个文本框)
- 通过查询将文本插入文本区域
- 单击插入文本或清理
- 当有人选择选项时,如何将MySQL中的数据插入文本区域
- 使用 jQuery/Javascript 将鼠标悬停在按钮上时将文本插入文本和帮助文本
- 在单个单词内插入文本.独特的环境