如何用JavaScript中的另一个字符串替换字符串

时间:2019-08-22 14:09:41

标签: javascript string replace

我正在尝试用另一个字符串替换字符串。

var string = "equity,40\n\
            equity-cap,15\n\
            cash,20\n";

var output = string.replace(name, `${name},${value}`);

//output 
output = "equity,40\n\
            equity-cap,15\n\
            cash,80,20\n"

var string = "equity,40\n\
            equity-cap,15\n\
            cash,20\n";

var text = cash
var value = 80

var string = "equity,40\n\
                equity-cap,15\n\
                cash,20\n";
var name = "cash";
var value = 80;
var output = string.replace(name, `${name},${value}`);

//output 
output = "equity,40\n\
                equity-cap,15\n\
                cash,80\n"

console.log(output, "required output")

var output = "equity,40\n\
            equity-cap,15\n\
            cash,80\n";

3 个答案:

答案 0 :(得分:1)

线索是您不会在代码中也尝试替换该值,因此最终会同时获得旧值和新值。

如果您知道旧值是20,则非常简单,我们只需将其添加到要替换的字符串中即可。

如果您不知道旧值是20,则由于我们必须搜索该值而变得更加困难。

我们可以使用正则表达式来做到这一点,该正则表达式还可以检测数字,无论数字是多少。

如果源数据来自CSV文件(我假定是由于字符串结构),我们还可以尝试利用CVS的结构来将字符串解析为实际对象。最大的优点是我们不必知道任何值(在这种情况下为20),您可以通过对象属性访问直接通过名称更改任何值。

PS:还有其他几种方法可以解决此问题,因此请使用对项目最有意义的方法。

// Option 1:
// If we know that the old value is 20:

var str_source = "equity,40\n\equity-cap,15\n\cash,20\n";

var name_to_replace = "cash";
var value_to_replace = 20;

var replacement_name = "cash";
var replacement_value = 80

var output = str_source.replace( `${ name_to_replace },${ value_to_replace }`, `${ replacement_name },${ replacement_value }`);

console.log( 'option 1:\n', output, '\n' );

// Option 2:
// If we do not know what the old value is.
// I think this string comes from a CSV file?
// So we can assume there's always either a \n character or end-of-line character after the number.
// We can create a Regular Expression that will look for the digits and the end of line.

var str_source = "equity,40\n\equity-cap,15\n\cash,20\n";

var name_to_replace = "cash";

var replacement_value = 80;
// Detect:
// the name_to_replace
// the comma following the name
// all digits following the comma
// one valid whitespace charater OR the end of the string
var regexp = new RegExp( `${ name_to_replace },\\d+?\\s|$` );

var output = str_source.replace( regexp, `${ name_to_replace },${ replacement_value }\n`);

console.log( 'option 2:\n', output, '\n' );

// Option 3:
// If this data really comes from a CSV file, we might as well just turn it into an object, so we don't have to manually search for specific values.
// We can just leverage splitting on commas and new lines to create
// an object we can edit directly by name.

var str_source = "equity,40\n\equity-cap,15\n\cash,20\n";

var name_to_replace = "cash";

var replacement_value = 80;

var combinations = str_source.trim().split( '\n' );
// Create the object so we get:
// { equity: "40", equity-cap: "15", cash: "20" }

var obj_source = combinations.reduce(( obj, combo ) => {
  var chunks = combo.split( ',' );
  obj[ chunks[0] ] = chunks[1];
  return obj
}, {});

// we can now just replace the value directly in the object:
obj_source[ name_to_replace ] = replacement_value;

// recreate the string from the object:
var output = Object
  .entries( obj_source )
  .map(([ key, value ]) => `${ key },${ value }` )
  .join( '\n' );
  
console.log( 'option 3:\n', output, '\n' );

答案 1 :(得分:0)

根据您的问题,似乎您想找到字符串的这一部分并用新的部分替换。如果符合您的要求,那么下面的代码将为您提供帮助。

  const str = "Hello World, It's a hello from the developer";
  const name = 'Hello';
  const value = 'Hi';

  const replaceString = (string, search, replaceWith) => {
    return string.split(search).join(replaceWith);
  };

  console.log(replaceString(str, name, value));
  console.log(replaceString('Hello...hello..Hello', name, value));

  

注意区分大小写

答案 2 :(得分:0)

您可以使用replace()替换另一字符串的一部分。我希望这会有所帮助。

var string = "equity,40\n\
              equity-cap,15\n\
              cash,20\n";
var name = 20;
var value = 80;

// string.replace("string which has to be changed", "string which is going to replace the previous string")
var output = string.replace(name, value);

console.log(output, "required output")