如何实现JavaScript选中文本替换时保留原空格?
Fix: Preserve Spaces When Replacing Selected Text with Asterisks
Got it, let's get this sorted! The issue with your current code is that it's replacing every character in the selected range with an asterisk—including spaces—because you're just creating a string of asterisks equal to the length of the selection. Instead, we need to target only non-space characters while leaving spaces untouched.
Here's the breakdown of the fix:
- First, actually grab the real selected text (not just a placeholder of asterisks)
- Use a regular expression to replace only non-space characters (
\Smatches any non-whitespace character) with asterisks - Keep spaces exactly as they are in the original selection
Modified Code
function getSel() { // obtain the object reference for the textarea var txtarea = document.getElementById("mytextarea"); // obtain the index of the first selected character var start = txtarea.selectionStart; // obtain the index of the last selected character var finish = txtarea.selectionEnd; // obtain all text var allText = txtarea.value; // obtain the actual selected text (this was missing before!) var selectedText = allText.substring(start, finish); // Replace ONLY non-space characters with asterisks var replacedText = selectedText.replace(/\S/g, '*'); // Build the new text string var newText = allText.substring(0, start) + replacedText + allText.substring(finish); txtarea.value = newText; $('#newpost').offset({ top: 0, left: 0 }).hide(); } $(document).ready(function () { var position; $('#newpost').hide(); $('#mytextarea') .on('select', function (e) { $('#newpost').offset(position).show(); var txtarea = document.getElementById("mytextarea"); var start = txtarea.selectionStart; var finish = txtarea.selectionEnd; // Update the preview to also preserve spaces var selectedText = txtarea.value.substring(start, finish); $('#newpost p').text(selectedText.replace(/\S/g, '*')); }) .on('mousedown', function (e) { position = { top: e.pageY -5, left: e.pageX}; }); $('#newpost').hide(); });
Key Changes Explained:
- Grabbing actual selected text: We now get
selectedText = allText.substring(start, finish)instead of generating a placeholder asterisk string. This lets us work with the real content of the selection. - Targeted replacement: The regex
/\S/gfinds every non-space character (\S) globally (gflag) in the selected text and replaces it with an asterisk. Spaces are left completely untouched. - Updated preview: We also fixed the preview text in the
selecthandler to match the actual replacement behavior, so the preview will correctly show spaces and asterisks as expected.
Now when you select text with spaces, only the non-space characters turn into asterisks—your spaces stay right where they are!
内容的提问来源于stack exchange,提问作者anub
相关产品推荐
相关产品推荐

