Search code examples
bookmarklet

easy way to remove all enter marks


The following code that I got from this page is working as expected.

How can I replace newlines/line breaks with spaces in javascript?

var words = "car\r\n\r\nhouse\nhome\rcomputer\ngo\n\nwent";
document.body.innerHTML = "<pre>OLD:\n" + words + "</pre>";
var new_words = words.replace(/[\r\n\x0B\x0C\u0085\u2028\u2029]+/g," ");
document.body.innerHTML += "<pre>NEW:\n" + new_words + "</pre>";

But in my case, the words variable is nothing but the text in the form and I am looking for a way to convert this script into a bookmarklet. How is the bookmarklet code different from regular one?


Solution

  • The first line just initiate the value in textarea for obviousness.

    document.querySelector('textarea').value =
      'car\r\n\r\nhouse\nhome\rcomputer\ngo\n\nwent';
    
    function replace() {
      const textarea = document.querySelector('textarea');
    
      textarea.value = textarea.value
        .replace(/[\r\n\x0B\x0C\u0085\u2028\u2029]+/g, ' ');
    }
    <textarea cols="50" rows="10"></textarea>
    
    <button onclick="replace();">Replace</button>

    Bookmarklet

    javascript: {
      const textarea = document.querySelector('textarea');
    
      void (textarea.value = textarea.value
        .replace(/[\r\n\x0B\x0C\u0085\u2028\u2029]+/g, ' '));
    }
    

    Bookmarklet to drag to bookmarks:

    <a href="javascript: {const textarea = document.querySelector('textarea'); void (textarea.value = textarea.value.replace(/[\r\n\x0B\x0C\u0085\u2028\u2029]+/g, ' '));}">Bookmarklet</a>