Hello. Guys, such a question. As in the regular season, at least in such

RegExp('[^\\d]|[\\s]', 'g') 

add the ability to use more and points to enter, and if you enter a comma or -, then replace the point?

I have a code

 inText.value = inText.value.replace( new RegExp( '[^\\d]|[\\s]', 'g' ), '' ); 

I want to make it so that if a point is entered, then it is normal, and if a comma or a dash, it replaces it with a point.

    4 answers 4

    One expression in JavaScript is not decisive. Do this:

     text.replace(/[^\\d.,-]/g, "").replace(/[,-]/g, "."); 

    upd
    Clearing everything except letters:

     text1.replace(/[^a-zа-я]/g, ""); 

    Floating point check:

     text2.replace(/(.)[,-]/g, "\\1.").replace(/^.*?(-?\\d+(?:\.\\d*)?).*$/, "\\1"); 

      And why not two regekspa? First RegExp('[,\\.\\-]', 'g') replace RegExp('[,\\.\\-]', 'g') with a dot, and then RegExp('[^\\d]|[\\s]|\\.', 'g') .

      • I do not really understand this. I have the inText.value = inText.value.replace (new RegExp ('[^ \\ d] | [\\ s]', 'g'), ''); I want to make it so that if a point is entered, then it is normal. if a comma or dash, then replaced by a period. - drop_off
       /(\d+)[\.\,\-]?(\d+)?/\1.\2/ 

      Why not assume that:

      • the integer part is always present (\ d +)
      • it may be followed by a comma or a minus [\. \, \ -]?
      • and after it MORE there are still numbers (\ d +)?

      Then substitute the value of the first bracket, the point, the value of the second bracket \ 1. \ 2 The only drawback is that even if there is nothing in the fractional part, there will still be a point after the whole.

        Explain the meaning of this: '[^\\d]|[\\s]'

        as for me, it’s enough [^\\d] because it already enters [^\\d] : [\\s]

        If you just need to select a number from a string, you can do something like this:

         var R = new RegExp('(\\d+)([,.]?)(\\d*)', 'g'); var str = '1999,89'; var num = str.replace(R, function(str, p1, p2, p3, offset, s){ if (p3=='') return p1; return p1+'.'+p3; }); alert(num); 
        • I initially did not correctly identified. I beg your pardon. 1 - you need to clean one field of everything except the letters azaya. 2 - you need to check the second field for a floating-point number and without. those. if entered 10 or 10.10 that is normal. If you entered 10.10 or 10-10, then replace the comma and dash with a period. - drop_off
        • @shurik, \ s - spaces, \ d - numbers, one into the other does not enter @dropoff, for the filter of letters it is safest to list all possible letters in square brackets, like [AB ... XYZab ... xyzABB ... yafbv ... i]. - beardog
        • @dropoff, read carefully: '[^\\d]|[\\s]' first one except digits, the second is whitespace. My answer is suitable for the second point. - Alex Kapustin