Replacing text on-the-fly in contenteditable with pure jQuery

I have seen a few questions about this on StackOverflow, but it seems hard to find a jQuery-based solution. Hence, I would like to ask this question.

I would like to replace text on-the-fly inside a div with the attribute contenteditable="true".

I'm looking for a jQuery-based solution that will do the following:

  • Automatically replace written text on-the-fly (as you type)
  • Being able to continue writing (whilst the replacement is being done)

I looked at SC Editor (http://www.sceditor.com/), it seems like it does exactly that (for instance, if you try type :) it gets replaced by an emoticon.

I think a good start would be an array with all the elements to replace:

$.settings = {
    path: 'https://example.com/images/',
    emoticons: {
        ':(' : 'stupid.jpg',
        ':)' : 'smart.jpg',
    }
}

I have been unable to find good examples of this. Would be happy if somebody can share their thoughts and any code regarding this.

How would the replacement get done in the best possible way, with the above code?


I found this. If you adjust it, it might suit your needs. It replaces { with {} and ( with () and the cursor ends up in the middle.

    <script type="text/javascript">
        $(document).ready(function () {
            $("#d").keypress(function (e) {


                    var charTyped = String.fromCharCode(e.which);
                    if (charTyped == "{" || charTyped == "(") {
                        // Handle this case ourselves
                        e.preventDefault();

                        var sel = window.getSelection();
                        if (sel.rangeCount > 0) {
                            // First, delete the existing selection
                            var range = sel.getRangeAt(0);
                            range.deleteContents();

                            // Insert a text node with the braces/parens
                            var text = (charTyped == ")") ? "{}" : "()";
                            var textNode = document.createTextNode(text);
                            range.insertNode(textNode);

                            // Move the selection to the middle of the text node
                            range.setStart(textNode, 1);
                            range.setEnd(textNode, 1);
                            sel.removeAllRanges();
                            sel.addRange(range);
                        }
                    }


            });
        });
    </script>
</head>

<body>
    <div id="d" contentEditable="true">....</div>
</body>
</html>

Getting plain text from user input on a contenteditable element, Getting plain text from user input on a contenteditable element box to be content aware and adapt its size dynamically (both width and height). So, replacing all the event handlers with a single MutationObserver allowed  Replace Div Content On The Fly With New Content. This is a tutorial for replacing the content in a div on-the-fly, without reloading the web page. It comes with several examples. Possible applications are: A constantly updated clock or countdown timer. Rotating ads - if one isn't clicked on within a minute, present a different one.


$('div').keyup(function(){
    //make here for loop which replace all emoticons
    $(this).text().replace(':(', 'stupid.jpg');
});

Making content editable, <div contenteditable="true"> This text can be edited by the user. provides a defaultParagraphSeparator command to allow you to change it. One very useful ability provided by JavaScript is the ability to replace the content of elements in an existing HTML document that was previously displayed, even empty elements. There are many reasons that a web designer may choose to take advantage of this ability but providing interactive pages is a likely goal.


Posting what I eventually wrote after failing to find an answer to this question. I hope that it will be helpful to someone else who comes to this question looking for an answer (:

I'm going to post a much more general find and replace solution (contained in a class). This is for content editable divs and works while the user is typing, additionally it does not affect the caret position. This implementation uses a case insensitive search (although it would be trivial to disable this in the code). Another advantage this has is that it will work even if you are typing in the middle of a paragraph (not just at the end of the line) and will work on pasted text. Give it a go!

class FindAndReplace {

	constructor($contentEditable, findAndReplaceData) {

		var self = this;

		$contentEditable.on('input blur', function () {

			var textNodes = self.getTextNodes($contentEditable);

			textNodes.each(function (i) {

				// Perform all replacements on text
				findAndReplaceData.forEach(function (findAndReplaceDatum) {

					var find = findAndReplaceDatum.find;
					var replace = findAndReplaceDatum.replace;

					var regexEscapedFind = self.escapeRegExp(find);
					var regexEscapedReplace = self.escapeRegExp(replace);

					var regexEscapedCaseInsensitiveFind = self.makeRegexCaseInsensitive(regexEscapedFind);

					// Case insensitive search for the find with a negative lookahead to check its not a case sensitive match of the replacement (aka to check its actually going to make a difference)
					var regexString = `(?!${regexEscapedReplace})${regexEscapedCaseInsensitiveFind}`;

					do {

						// Get the latest version of the text node
						textNode = self.getTextNodes($contentEditable)[i];
						var text = textNode.data;

						var regex = new RegExp(regexString);
						var matchIndex = text.search(regex);
						var matchFound = (matchIndex !== -1);

						if (matchFound) {

							// Select the match
							var range = document.createRange();
							range.setStart(textNode, matchIndex);
							range.setEnd(textNode, matchIndex + find.length);
							// Delete it
							range.deleteContents();

							// Create the replacement node
							var textNode = document.createTextNode(replace);
							// Insert it
							range.insertNode(textNode);

							// Set the range to the end of the selected node
							range.collapse(false);
							// Set the user selection the range
							var sel = window.getSelection();
							sel.removeAllRanges();
							sel.addRange(range);

							// Make sure there a no adjacent or empty text nodes
							$contentEditable[0].normalize();

						}

					} while (matchFound)

				});

			});

		});

	}

	escapeRegExp(string) {

		// https://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex
		return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string

	}

	getTextNodes($contentEditable) {
		return $contentEditable.contents().filter(function () {
			return this.nodeType == 3; // Text node
		});

	}

	makeRegexCaseInsensitive(string) {

		var stringArray = string.split('');

		stringArray = stringArray.map(function (char) {

			if (char.toLowerCase() !== char.toUpperCase())
				return '[' + char.toLowerCase() + char.toUpperCase() + ']';
			else
				return char;

		});

		return stringArray.join('');

	}

}
div {
  border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script>

$(function(){

  var findAndReplaceData = [
	  {
      'find': 'find me',
      'replace': 'and replace with me!'
    },
    {
      'find': 'foo',
      'replace': 'bar'
    },
    {
      'find': 'no',
      'replace': 'yes'
    }
  ];

  $contentEditable = $('div');

  new FindAndReplace($contentEditable,findAndReplaceData);

});

</script>

<div contenteditable="true"></div>

Convert your Browser into a Notepad with HTML5 contenteditable , To save the text that you typed, press Ctrl+s keys and choose a location to save the file It does not allow users to edit or change the contents of a page. In addition, it allows you to save the contents in a .txt format using JavaScript and jQuery. THE TEXT TO A BLOB. var textToBLOB = new Blob([Value], { type: 'text/​plain' });  Today, I'd like to cover how to get, set, and update a cell's contents on the fly. Fetching a Cell's Contents The main challenge when working with cell contents is that they may contain just about any type of HTML element, in addition to text - including other tables!


Div Contenteditable Onchange, Setting the cursor in a contenteditable div, IE only btw!, is not a trivial thing, which attempts to make it easier to use contentEditable to edit plain text. This is a tutorial for replacing the content in a div on-the-fly, without reloading the web page. I have used jQuery UI library to change the position of the meme text over the  The .on() method attaches event handlers to the currently selected set of elements in the jQuery object. As of jQuery 1.7, the .on() method provides all functionality required for attaching event handlers. For help in converting from older jQuery event methods, see .bind(), .delegate(), and .live(). To remove events bound with .on(), see .off().


yabwe/medium-editor: Medium.com WYSIWYG editor clone , Uses contenteditable API to implement a rich text solution. pairs (2 element arrays) of RegExp and replacement text to use during paste when It is possible to dynamically add new elements to your existing MediumEditor instance: removeElements('#myElement'); // in case you have jQuery and don't exactly know  5 Replacing text on-the-fly in contenteditable with pure jQuery; View more network posts → Top tags (3) linux. Score 0. Posts 1. gnu-screen. Score 0. Posts 1.


The contenteditable attribute, Now with the contenteditable attribute, things have got a whole lot easier. The contenteditable attribute was mainly intended for providing an in-browser rich-​text or the editable field and send an Ajax post to your server with the change. You can make one project-wide jQuery method that binds to any  The contentEditable attribute makes this task a lot easier. All you have to do is set this attribute to true and standard HTML5 elements will become editable. In this tutorial, we will create an inline rich text editor based on this feature.