简体   繁体   English

Javascript或JQuery如何替换字符串中的所有“ +”

[英]Javascript or JQuery how to replace all '+' in a string

Right now I have a variable which is storing a string. 现在,我有一个存储字符串的变量。

var value = "66+88";

How can I replace '+' with a standard + operator so that I can evaluate 如何用标准+运算符替换“ +”,以便我可以评估

66 + 88 = 154 66 + 88 = 154

Thanks 谢谢

Use String#split , Array#map it to get Number and then Array#reduce 使用String#splitArray#map将其获取Number ,然后使用Array#reduce

 var value = "66+88"; var result = value.split('+').map(Number).reduce(function(a, b) { return a + b; }, 0); console.log(result); 

You can use eval for this: 您可以为此使用eval

var value = eval("66+88");

But you need to be careful, especially if this string come's from user. 但是您需要小心,特别是如果此字符串来自用户。

This function will evaluate input string as JavaScript and can damage your other scripts or can be used for hacker attacks. 此函数会将输入字符串评估为JavaScript,并可能损坏您的其他脚本或可用于黑客攻击。

Use it at your own risk! 需要您自担风险使用它!

Use String#replace 使用String#replace

 var value = "66+88"; var result = value.replace(/^(\\d+)\\+(\\d+)$/, function(x, y, z){ return parseInt(y) + parseInt(z) }) console.log(result); 

You can use split() method to split the string. 您可以使用split()方法分割字符串。

var value = "66+88";
var no = value.split('+');
console.log(parseInt(no[0]) + parseInt(no[1]));

split() method will return an array . split()方法将返回一个array In this case 在这种情况下

no = ['66','88'] 否= ['66','88']

parseInt() will convert string to Int and you can calculate the sum. parseInt()会将字符串转换为Int,您可以计算总和。

Thanks! 谢谢!

You could use split and reduce to sum up your string. 您可以使用splitreduce来总结您的字符串。

Here is an example. 这是一个例子。

 var value1 = "66+88"; var value2 = "66+88+44"; function sumUpStr (strToSum) { var sum = strToSum.split("+").reduce(function(prev, next) { return +prev + +next; }); return sum; }; console.log("Sum of value1 is: " + sumUpStr(value1)); console.log("Sum of value2 is: " + sumUpStr(value2)); console.log("Sum of value1 + value2 is: " + sumUpStr(value1 + "+" + value2)); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM