skip to Main Content

Required to replace with empty('') on unwanted string using regexp not works as expected.
if I try to replace the start group it works (^w*). But I could not able to select the post fix of the number.(D*$). how to combine both or what this the correct syntax to replace.

example:

--123 should be -123
a-123 should be -123
!-123- should be -123
+-123.44x should be -123.44
--123.33- should be -123.33

any one help me?

when I try this get no output as expected .replace(/[^-d.]D*$/g, ""))

3

Answers


  1. you could do it like this:

    function cleanString(str) {
      return str.replace(/^w*|D*$/g, '');
    }
    
    • ^w*: This removes any word characters at the start.
      |: OR
    • D*$: This removes any non-digit characters at the end.
    • g: Global flag, to replace all instances.
    Login or Signup to reply.
  2. Write a regexp that matches what you want to keep. Put .* around it to match the rest of the string, and replace with just the captured text.

    str = str.replace(/.*(-d+(?:.d+)?).*/, "$1");
    

    DEMO

    Login or Signup to reply.
  3. You may use following regex for search:

    ^D*(?:(?=-)|D)|D+$
    

    and replace it with just an empty string.

    Code Demo

    Code:

    const rx = /^D*(?:(?=-)|D)|D+$/g;
    
    ['--123',
    'a-123',
    '-x123',
    'ab123',
    '!-123',
    '+-123.44x',
    '--123.33-'].forEach(
       el => console.log(el, ' => ', el.replace(rx, ''))
    );

    RegEx Details:

    • ^: Start
    • D*: Match 0 or more non-digits
    • (?:: Start non-capture group
      • (?=-): We have a - at next position
      • |: OR
      • D: Match any character that is not a digit
    • ): End non-capture group
    • |: OR
    • D+: Match 1+ non-digits
    • $: End
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search