skip to Main Content

i want to replace string from

"I am master at string" to "I zm master zt string"

I don not want to replace all character ‘a’ or only first character i want to replace only those character which starts with ‘a’ if word have ‘a’ in between it should not replaced

in string there is method called replace() but with replace we can only change first occurance or using with regx g we can replace all the character but i want to replace all ‘a’ character with ‘z’ , only if ‘a’ is at first position in word. how can do with javascript

3

Answers


  1. You can use a combination of the split() method to break the string into words, and then iterate through the words to check if the first character is ‘a’. If it is, replace the ‘a’ with ‘z’. Finally, use the join() method to reassemble the string.

    function replaceFirstChar(inputStr, searchChar, replaceChar) {
      // Split the string into words
      const words = inputStr.split(" ");
    
      // Iterate through the words and replace the first character if it matches searchChar
      const updatedWords = words.map(word => {
        if (word[0] === searchChar) {
          return replaceChar + word.slice(1);
        }
        return word;
      });
    
      // Join the updated words back into a single string
      return updatedWords.join(" ");
    }
    
    const inputString = "I am master at string";
    const outputString = replaceFirstChar(inputString, 'a', 'z');
    console.log(outputString); // Output: "I zm master zt string"

    edit:

    as @evolutionxbox points out, you can simply use the following regular expression:

    console.log("I am master at string".replaceAll(/ba/g, 'z'));
    Login or Signup to reply.
  2. You can preserve case if you transform the matched letter to a char code, add 25, and convert back into a letter.

    Note: The b (word boundary) before the target letter means start of word, and the ig flags toggle case-insensitive and global replace repectively.

    console.log(
      'I am master at string'
        .replace(/b(a)/ig, (g) =>
          String.fromCharCode(g.charCodeAt(0) + 25)));

    Here is a functional example:

    // Look Ma, no magic numbers!
    const
      CHAR_LOWER_A = 'a'.charCodeAt(0), //  97
      CHAR_LOWER_Z = 'z'.charCodeAt(0), // 122
      CHAR_UPPER_A = 'A'.charCodeAt(0), //  65
      CHAR_UPPER_Z = 'Z'.charCodeAt(0); //  90
    
    const subFirstLetters = (str, from, to) => {
      const
        targetOffset = to.toLowerCase().charCodeAt(0) - CHAR_LOWER_A,
        expression = new RegExp(`\b(${from})`, 'ig');
      return str.replace(expression, (g) => {
        const sourceOffset = g.charCodeAt(0);
        if (sourceOffset >= CHAR_UPPER_A && sourceOffset <= CHAR_UPPER_Z) {
          return String.fromCharCode(targetOffset + CHAR_UPPER_A);
        } else if (sourceOffset >= CHAR_LOWER_A && sourceOffset <= CHAR_LOWER_Z) {
          return String.fromCharCode(targetOffset + CHAR_LOWER_A);
        }
        return g;
      });
    };
    
    // I am the Waster of strings, wwahaha!
    console.log(subFirstLetters('I am the Master of strings, mwahaha!', 'm', 'w'));
    Login or Signup to reply.
  3. Approach without regex. You can use .split got get an array of words. Use map with a condition (ternary syntax): if a word starts with "a", "z" is added as the first letter using a string literal and the the rest of the word using substring. Otherwise the word is unchanged. At the end, array is converted to string with join.

    const replace = input => input
      .split(' ')
      .map(word => (word.startsWith('a') ? `z${word.substring(1)}` : word))
      .join(' ');
    
    const input = "I am master at string";
    const output = replace(input);
    
    console.log(output); 
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search