skip to Main Content

i have tried to remove first two character and space form starting of string but not able to do that.

like i have tried

let check = 'aa hello world'
check.replace(/^(.){2}/,'').trim()
let check = 'ab hello world'
check.replace(/^(.){2}/,'').trim()
let check = 'hello world'
check.replace(/^(.){2}/,'').trim()

only we remove specific aa,ab

i tried two replace first aa and ab with space with this syntax
replace(/^(.){2}/,”).trim() but not work.

If any body help me out.

i tried two replace first aa and ab with space with this syntax
replace(/^(.){2}/,”).trim() but not work.

like i have tried to remove first aa and ab only print hello word but not work with this syntax
let check = ‘aa hello world’
let check = ‘ab hello world’

2

Answers


  1. Can you try using slice

    let text = "aa hello world!";
    if (text.startsWith('aa') || text.startsWith('ab')) {
     text = text.slice(3);
    }
    

    Result:

    hello world
    
    Login or Signup to reply.
  2. Here is an example just adding an IF statement to see if the string starts with aa or ab:

     var check = 'aa hello world';
    
     if (check.startsWith('aa') || check.startsWith('ab')) {
       check = check.substring(3);
     }
    

    You can even keep your code:

    var check = 'aa hello world';
    
    if (check.startsWith('aa') || check.startsWith('ab')) {
      check = check.replace(/^(.){2}/,'').trim()
    }
    
    console.log(check)
    

    Answer:

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