skip to Main Content

hi how can we find and access the first letters that comes right after the replaceAll() ?
like we have : hi_my name is_reza => replaceAll("_"," ") => so now i want to access to (m) from my and to (r) from reza

id did try split() and indexOf() method but it just aiming one of underscores not all of them

4

Answers


  1. Chosen as BEST ANSWER

    thank you all . actually i was looking for a way to remove all underlines and replacing the first letter after them to be capital . so i used your solution to achieve that .

    const str = "hi_my name is_reza";
    const d = str
      .split("_")
      .map((word, index) => {
        return index !== 0 ? word.charAt(0).toUpperCase() + word.slice(1) : word;
      })
      .join(" ")
      .replaceAll("_", " ");
    
    console.log(d);


  2. You can use split, slice (start from index 1 to the end, because you don’t want the left part of the first ‘_’) and map (which execute over every element of an array) on hi_my name is_reza like so :

    const str = "hi_my name is_reza";
    const d = str.split("_").slice(1).map(e =>e[0]);
    
    console.log(d);
    Login or Signup to reply.
  3. The get the first character(s) after _ underscore, you could use:

    const str = "hi_my name is_reza";
    console.log(str.match(/(?<=_)./g))

    or with /(?<=_)[^_]/g

    Demo on Regex101.com

    To change that letter after _ (in order to capitalize it) and remove the underscore all in one go, you could use String.prototype.replace() like:

    const str = "hi_my name is_reza";
    const output = str.replace(/_(.)/g, (m, m1) => ` ${m1.toUpperCase()}`)
    console.log(output)
    Login or Signup to reply.
  4. By this, you can do both replace and get those string after _

    let str = 'hi_my name is_reza';
    let res = [];
    const final = str.replaceAll(/_/g,function(r,index){
      res.push(str[index+1]);
      return ' '
    });
    
    console.log(final,res)// by this you can replace and get the string after _
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search