[英]How to insert character before another specific character using javascript
I need to know how to insert an asterix before an open bracket. 我需要知道如何在开括号之前插入星号。
I am doing multiplication using javascript's eval
, for example, eval("2(3)")
, but I am getting the error "unexpected input value"
. 我正在使用javascript的
eval
进行乘法,例如eval("2(3)")
,但出现错误"unexpected input value"
。
To solve this I need the following: 为了解决这个问题,我需要以下几点:
var str = "2(3)";
to be changed to this: 更改为:
output = "2*(3)";
You can use String.prototype.replace() . 您可以使用String.prototype.replace() 。
Example: 例:
var str = '2(3)' var output = str.replace(/\\(/g, '*(') console.log(output)
That will output: 2*(3)
将会输出:
2*(3)
If you want to perform more complex/nested multiplication you need to use this more complicated regex (\\)|\\d+(?!\\d)\\.?)(?=[(\\d.+-])
with the replace()
function. It will work for any combination of nested brackets, as well as plus signs, negative numbers and numbers starting or ending with a decimal point: 如果要执行更复杂/嵌套的乘法,则需要使用带有
replace()
(\\)|\\d+(?!\\d)\\.?)(?=[(\\d.+-])
更复杂正则表达式(\\)|\\d+(?!\\d)\\.?)(?=[(\\d.+-])
replace()
函数,适用于嵌套括号,加号,负数以及以小数点开头或结尾的数字的任意组合:
var str, output; str = '2(3)'; output = str.replace(/(\\)|\\d+(?!\\d)\\.?)(?=[(\\d.+-])/g, '$1*'); console.log(output); str = '2(3)(-4)'; output = str.replace(/(\\)|\\d+(?!\\d)\\.?)(?=[(\\d.+-])/g, '$1*'); console.log(output); str = '((.22(33))((-44)-55.(66)+77))'; output = str.replace(/(\\)|\\d+(?!\\d)\\.?)(?=[(\\d.+-])/g, '$1*'); console.log(output);
You can use the replace()
function combined with a little regex ([0-9])\\(([0-9])
: 您可以将
replace()
函数与少许正则表达式([0-9])\\(([0-9])
:
var str = "2(3)"; var output = str.replace(/([0-9])\\(([0-9])/g,'$1*($2'); console.log(output);
You can slice the string and add the asterisk sign like this: 您可以对字符串进行切片并添加星号,如下所示:
var str = "2(3)"; var new_str = str.slice(0, str.indexOf("(")) + "*" + str.slice(str.indexOf("(")); console.log(new_str)
Try this: 尝试这个:
var str = "2(3)"; var a = str.split(''); a.splice(1,0,"*"); a = a.join(''); console.log(a);
Works good for me :) 对我有用:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.