skip to Main Content

I tried to remove string using nodejs

const replace = "1."
const replacer = new RegExp(replace, 'g', '')

function removeText() {
    let originalText = '
1. I can own unlimited wealth on this earth
2. My potential for wealth knows no bounds
3. I attract limitless financial opportunities
    ';
    
    let newText = originalText.replace(replacer, '');

    console.log(newText);
}

removeText();

using this code I can only remove "1." but what about 2., 3., I have this counting upto 100, can someone help me?

3

Answers


  1. Chosen as BEST ANSWER

    I found the answer. There is a common pattern going on in the sentences, we want to remove all the numbers, and they all end up with a dot(.) in the end.

    let newText = originalText.replace(/[0-9]./g, '');
    

    This code block will check wether the text starts with a number and ends up with a dot, if both of these conditions meet in a single text, then it will be removed from the string. Have a great day. ☺️


  2. split the string by lines. Filter out the empty values. Split each line by number followed by dot and finally join them back with new line.

    let originalText = `
    1. I can own unlimited wealth on this earth
    2. My potential for wealth knows no bounds
    3. I attract limitless financial opportunities
        `;
    
    originalText=originalText.split('n').filter(l=>l).map(line=>line.split(/d+.s/)[1]).join('n')
    
    Login or Signup to reply.
  3. You can simply achieve this by just using digit RegEx.

    Live Demo :

    let originalText = `
    1. I can own unlimited wealth on this earth
    2. My potential for wealth knows no bounds
    3. I attract limitless financial opportunities
    `;
    
    let newText = originalText.replace(/d./g, '');
    
    console.log(newText);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search