Regex to replace multiple spaces with a single space

后端 未结 23 2590
北恋
北恋 2020-11-22 10:00

Given a string like:

\"The dog      has a long   tail, and it     is RED!\"

What kind of jQuery or JavaScript magic can be used to keep spaces to only o

23条回答
  •  执念已碎
    2020-11-22 10:07

    Comprehensive unencrypted answer for newbies et al.

    This is for all of the dummies like me who test the scripts written by some of you guys which do not work.

    The following 3 examples are the steps I took to remove special characters AND extra spaces on the following 3 websites (all of which work perfectly) {1. EtaVisa.com 2. EtaStatus.com 3. Tikun.com} so I know that these work perfectly.

    We have chained these together with over 50 at a time and NO problems.

    // This removed special characters + 0-9 and allows for just letters (upper and LOWER case)

    function NoDoublesPls1()
    {
    var str=document.getElementById("NoDoubles1");
    var regex=/[^a-z]/gi;
    str.value=str.value.replace(regex ,"");
    }
    

    // This removed special characters and allows for just letters (upper and LOWER case) and 0-9 AND spaces

    function NoDoublesPls2()
    {
    var str=document.getElementById("NoDoubles2");
    var regex=/[^a-z 0-9]/gi;
    str.value=str.value.replace(regex ,"");
    }
    

    // This removed special characters and allows for just letters (upper and LOWER case) and 0-9 AND spaces // The .replace(/\s\s+/g, " ") at the end removes excessive spaces // when I used single quotes, it did not work.

    function NoDoublesPls3()
    {    var str=document.getElementById("NoDoubles3");
    var regex=/[^a-z 0-9]/gi;
    str.value=str.value.replace(regex ,"") .replace(/\s\s+/g, " ");
    }
    

    ::NEXT:: Save #3 as a .js // I called mine NoDoubles.js

    ::NEXT:: Include your JS into your page

     
    

    Include this in your form field:: such as

    
    

    So that it looks like this

    
    

    This will remove special characters, allow for single spaces and remove extra spaces.

提交回复
热议问题