【问题标题】:How to replace a char from a string with a specified text?如何用指定的文本替换字符串中的字符?
【发布时间】:2021-09-11 00:10:15
【问题描述】:

我想写一个函数,当给出一个字符串时,它会自动用指定的值替换字符串。 例如:-

let name = 'app';
valueReplace(name);

function valueReplace(value){
//Have to change char 'a' 'p' 'p' with the values given below 

let a = '2G8D';
let p = '7K5A';

/*
Code that will help to do this
*/

}


【问题讨论】:

  • 在 Stackoverflow 上,通常希望您自己付出一些努力来解决问题,然后询问您遇到的问题。这通常不是一个要求人们为您完全实施某些东西的地方。

标签: javascript string function replace substring


【解决方案1】:

您可以为此使用正则表达式

let name = 'app';
console.log(valueReplace(name));

function valueReplace(value){
//Have to change char 'a' 'p' 'p' with the values given below 
  let a = '2G8D';
  let p = '7K5A';
  return value.replace(/a/g, "2G8D").replace(/p/g, "7K5A");


}

【讨论】:

    【解决方案2】:
    const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';
    
    console.log(p.replace('dog', 'monkey'));
    // expected output: "The quick brown fox jumps over the lazy monkey. If the dog reacted, was it really lazy?"
    
    
    const regex = /Dog/i;
    console.log(p.replace(regex, 'ferret'));
    // expected output: "The quick brown fox jumps over the lazy ferret. If the dog reacted, was it really lazy?"
    

    Reference

    【讨论】:

      猜你喜欢
      • 2021-06-21
      • 1970-01-01
      • 2015-05-19
      • 1970-01-01
      • 2023-03-25
      • 2011-02-13
      • 1970-01-01
      • 2016-08-27
      • 2014-01-26
      相关资源
      最近更新 更多