我正在尝试编写一个字符串或整数公式,它将在括号中查看代码。我的逻辑是这样的:搜索第一个括号,找到最后的括号,并返回其间的所有内容。我确定有一个字符串或整数函数,但不确定哪一个会做的伎俩。顺便说一下,括号之间的代码长度从3到9不等。请检查此代码在此输入代码
var n;
var $;
var str = document.getElementById("demo").innerHTML;
var p = str.indexOf(")");
var q = str.indexOf("(");
var res = str.replace(")", "");
var re = str.replace("(", "");
document.getElementById("demo").innerHTML = res;
var k = str.replace("$", "(" + "$")
.replace(/,$/, ".")
.replace(")", "(" + res + ")")
.replace("(", "(" + res + ")")
.replace(/O/g, 0)
.replace(/o/g, 0)
.replace(/g/g, 9)
.replace(/\s/g, "");
document.getElementById("demo3").innerHTML = k;
答案 0 :(得分:3)
从我对你的问题的理解,你只想搜索一串任何东西,并拉出被paranthesis包围的字符。这很容易。
var foo = 'blah(capture this)blah';
var result = foo.match(/\(([^()]+)\)/);
//this simply says: capture any characters surrounded by paranthesis, as long as there is at least one character.
console.log(result[1]);
逻辑非常容易理解。
var regex = new RegExp(
'\\(?'+ //optional (
'\\$?'+ //optional $
'(\\d+)' //capture any digit, at least one
);
function format(userInput) {
var results = userInput.match(regex);
if (results === null) { results = [0,0]; }
//get the important part (the digits), format it however you want.
var formatted = '($'+results[1]+'.00)';
return formatted;
}
//all output ($1234.00)
console.log(format('$1234)'));
console.log(format('($1234.00'));
console.log(format('1234'));
console.log(format('1234.0'));
console.log(format('1234)'));
console.log(format('(1234.0'));