我想制作一个简单的工具来替换间隙/下划线的选定文本。我已经有了这个功能,但我想改进它,使下划线与所选文本所包含的字符(包括空格)一样多。
这不是重复,因为的想法是使其与JSFiddle的工作方式相同;它必须采用所选文本,并在那里替换它,如JSFiddle。
当前的JS:
$(document).ready(function() {
$('#btn_convert_to_gaps').click(function() {
document.execCommand('insertText', true, "________");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn_convert_to_gaps"><b>Convert selected to gaps</b>
</button>
<div id='fake_textarea' contenteditable>
Select some text and click the button to make it bold...
<br>Or write your own text
</div>
示例:
答案 0 :(得分:1)
这符合您的要求,改编自Repeat Character N Times
function replaceWithUnderscores(text, term) {
return text.replace(term, Array(term.length).join('_'));
}
console.log(replaceWithUnderscores("this sentence", "is se"));
此问题介绍了如何选择文字:Get the Highlighted/Selected text 这个问题讨论了如何做同样的事情(但是来自textarea):How to get selected text from textbox control with javascript
$(document).ready(function() {
$('#btn_convert_to_gaps').click(function() {
var term = window.getSelection().toString();
document.execCommand('insertText', true, Array(term.length).join('_'));
});
});
答案 1 :(得分:0)
您可以尝试这种方法。整个想法是使用所选文本中的字符长度来创建要替换的整个字符串。
var charToReplaceWith = '_'; // configurable
$('#btn_convert_to_gaps').click(function()
{
var i = 1;
var textToReplaceWith = charToReplaceWith; // declare a local variable that would replace the selection with
while( i < window.getSelection().toString().length) // iterate through the length and build the replace text, this would also take care of spaces
{
textToReplaceWith += charToReplaceWith;
i++;
}
$("#fake_textarea").text($("#fake_textarea").text().replace(window.getSelection(),textToReplaceWith));
});