如何使用 javascript 仅当 'a' 在单词的第一个位置时才用 'z' 替换 'a' 字符

问题描述 投票:0回答:3

我想替换字符串

“我是弦乐高手”到“我是 zm 高手 zt 弦乐”

我不想替换所有字符“a”或仅替换第一个字符我只想替换那些以“a”开头的字符,如果单词之间有“a”则不应替换

在字符串中有一个名为 replace() 的方法,但使用 replace 我们只能更改第一次出现或使用 regx g 我们可以替换所有字符但我想用 'z' 替换所有 'a' 字符,只有 'a'在单词的第一个位置。如何使用 javascript

javascript string replace
3个回答
1
投票

如果将匹配的字母转换为字符代码,加 25,然后转换回字母,则可以保留大小写。

注意:目标字母前的

\b
(单词边界)表示单词的开头,
ig
标志分别切换不区分大小写和全局替换。

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

这是一个功能示例:

// 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'));


0
投票

您可以结合使用

split()
方法将字符串分解为单词,然后遍历单词以检查第一个字符是否为'a'。如果是,请将“a”替换为“z”。最后,使用
join()
方法重新组合字符串。

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"

编辑:

正如@evolutionxbox 指出的那样,您可以简单地使用以下正则表达式:

console.log("I am master at string".replaceAll(/\ba/g, 'z'));


0
投票

您可以编写一个通用函数,使用 JavaScript 将单词中第一次出现的字符“a”替换为“z”。这是一个例子:

 function replaceFirstChar(word, oldChar, newChar) {
  if (word.charAt(0) === oldChar) {
    word = word.replace(new RegExp("^" + oldChar), newChar);
  }
  return word;
}

此函数采用三个参数:要修改的单词、要替换的 oldChar 字符和要替换为的 newChar 字符。

在函数内部,charAt()方法用于检查word变量的第一个字符是否与传入函数的oldChar字符相同。如果是,则将 replace() 方法与匹配单词中第一次出现的 oldChar 字符的正则表达式一起使用,并将其替换为 newChar 字符。

以下是该函数的用法示例:

let word = "apple";
word = replaceFirstChar(word, "a", "z");
console.log(word); // "zpple"

在这个例子中,word 变量连同 oldChar 字符“a”和 newChar 字符“z”一起传递给 replaceFirstChar() 函数。该函数用“z”替换单词中的第一个“a”字符,并返回修改后的单词。

© www.soinside.com 2019 - 2024. All rights reserved.