Search code examples
javascripttext

javascript: Detect and remove invisible characters when pasting text


I copied a text from a source and pasted it in a textarea.
In the textarea, the text looks OK, but when I paste the text in a text editor like Sublime Text, here's what I see : the string contains some invisible characters in place of 2 spaces (<0x03>).

What are these characters ? Where do they come from ?
With Javascript, how can I detect these and replace with "real" spaces

enter image description here

Thank you.


Solution

  • The most easy way to do this just use replace method

    let inputString = "Lorem ipsum <0x03> dolor <0x03>";
    
    let modifiedString = inputString.replace(/<0x03>/g, ' ');
    
    console.log(modifiedString);
    

    UPDATE:

    For finding character with code we can use regular expression:

    let inputString = "Lorem ipsum <0x03> dolor <0x03>";
    
    let modifiedString = inputString.replace(/\x03/g, ' ');
    
    
    console.log(modifiedString);