javascript - 如何在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";
解决方案
线索是您并没有尝试替换代码中的值,因此您最终得到了旧值和新值。
如果您知道旧值是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' );
推荐阅读
- python - 为什么索引给出完全错误的输出?
- c++ - 发送源代码时省略未使用的 boost src 文件的策略
- php - (#12) analytics_app_events_exports 对于 v3.0 及更高版本已弃用
- r - 绘图大小 = 1/{N∗⌈log2N⌉∗[(1/70)/60]} 在 R 中?
- javascript - 如何将队列中的重复数据添加到 JavaScript 数组中?
- svg - SVG 徽标上带圆圈的文本(顶部和底部)
- javascript - 表单数据未发布
- javascript - CRM 2011 调用 Ajax 给出错误请求错误
- typescript - Javascript/Typescript 默认顺序排序
- javascript - 如何添加 2 个不同 div 中的按钮?