skip to Main Content

So, I have a string something like, asd.asd.asd.234432$$..asd888. Now I want to get a string like, .234432888. So what I want to achieve is to remove every dots except for the first one and remove every non number character.

So far I tried *string*.replace(/[^d.]/gi, new String()). But, it does not work as expected.

4

Answers


  1. Do a global regex match of characters:

    • (?<!..*) – find . that doesn’t have . before it at any distance (.*) using a lookbehind negative assertion. That would be the first . encountered.
    • d+ – find all numbers
    • join the found characters:
    const str = 'asd.asd.asd.234432$$..asd888';
    
    console.log(str.match(/(?<!..*).|d+/g).join(''));
    Login or Signup to reply.
  2. You can use (?<=.[^.]*).|[^d.]+ regex and replace it with empty string.

    Here (?<=.[^.]*). part matches all dots except first dot and [^d.]+ matches any non-digit non-dot one or more character.

    Demo

    JS code demo,

    let s = 'asd.asd.asd.234432$$..asd888';
    console.log(s, ' --> ', s.replace(/(?<=.[^.]*).|[^d.]+/g, ''));
    Login or Signup to reply.
  3. const inputString = 'asd.asd.asd.234432$$..asd888';
    
    const transformedString = inputString.replace(/(..*?)./g, '$1').replace(/[^d.]/g, '');
    
    console.log(transformedString);
    
    Login or Signup to reply.
  4. Possible and easier with the string.match():

    string.match(/(.)(?:[^0-8](d+))*/).join('');
    

    Also, there’s a thing that you should be aware of: In [], you can’t use special statements such as d[d] is treated as „ or d“. You need to use character range such as 0-9.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search