首页 > 解决方案 > 如何在javascript中用另一个字符串替换字符串

问题描述

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

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";

标签: javascriptstringreplace

解决方案


线索是您并没有尝试替换代码中的值,因此您最终得到了旧值和新值。

如果您知道旧值是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' );


推荐阅读