Javascript 正则表达式[任何数字]
我需要在javascript中测试字符串中的“[任何数字]”。我该如何匹配它 哦,“[”和“]”也需要匹配 所以像“[1]”或“[12345]”这样的字符串是匹配的 不匹配:“[23432”或“1]” 例如:Javascript 正则表达式[任何数字],javascript,jquery,regex,Javascript,Jquery,Regex,我需要在javascript中测试字符串中的“[任何数字]”。我该如何匹配它 哦,“[”和“]”也需要匹配 所以像“[1]”或“[12345]”这样的字符串是匹配的 不匹配:“[23432”或“1]” 例如: $('.form .section .parent').find('input.text').each(function(index){ $(this).attr("name", $(this).attr("name").replace("[current]", "['"+in
$('.form .section .parent').find('input.text').each(function(index){
$(this).attr("name", $(this).attr("name").replace("[current]", "['"+index+"']"));
});
我需要将输入字段名称“items[0].firstname”替换为“items[1].firstname”
感谢更新:您的更新问题
variable.match(/\[[0-9]+\]/);
试试这个:
variable.match(/[0-9]+/); // for unsigned integers
variable.match(/[-0-9]+/); // for signed integers
variable.match(/[-.0-9]+/); // for signed float numbers
希望这有帮助 您可以使用以下函数查找任何字符串中最大的
[number]
var mask = /^\d+$/;
if ( myString.exec(mask) ){
/* That's a number */
}
它以整数形式返回最大的[number]
值
var biggestNumber = function(str) {
var pattern = /\[([0-9]+)\]/g, match, biggest = 0;
while ((match = pattern.exec(str)) !== null) {
if (match.index === pattern.lastIndex) {
pattern.lastIndex++;
}
match[1] = parseInt(match[1]);
if(biggest < match[1]) {
biggest = match[1];
}
}
return biggest;
}
var biggestNumber=函数(str){
var模式=/\[([0-9]+)\]/g,匹配,最大值=0;
while((match=pattern.exec(str))!==null){
if(match.index==pattern.lastIndex){
pattern.lastIndex++;
}
match[1]=parseInt(match[1]);
如果(最大值<匹配[1]){
最大=匹配[1];
}
}
回报最大;
}
演示 下面的演示将计算每次单击按钮时文本区域中的最大数字 它允许您使用textarea,并使用不同的文本重新测试函数
var biggestNumber=函数(str){
var模式=/\[([0-9]+)\]/g,匹配,最大值=0;
while((match=pattern.exec(str))!==null){
if(match.index==pattern.lastIndex){
pattern.lastIndex++;
}
match[1]=parseInt(match[1]);
如果(最大值<匹配[1]){
最大=匹配[1];
}
}
回报最大;
}
document.getElementById(“myButton”).addEventListener(“单击”,函数(){
警报(最大编号(document.getElementById(“myTextArea”).value));
});代码>
这是一个测试[1]这[2]也是一个测试
这又是一次考验。
items[14]。items[29]。firstname也是一个测试!
项目[4]。名字也是一个测试!
试试我
我尝试了这个$(this.attr(“name”),$(this.attr(“name”)。替换(“/\[[0-9]+\]/”,“['”+索引+“]”);但它不起作用。我做错什么了吗?没关系。它确实有效:var name=$(this.attr(“name”);var newname=$(this.attr(“name”).replace(name.match(/\[[0-9]+\]/),“[”+索引+“])@aorcsik Life saver:)/[-.0-9]+/
只匹配一个句点,而不是真正匹配的数字。
var biggestNumber = function(str) {
var pattern = /\[([0-9]+)\]/g, match, biggest = 0;
while ((match = pattern.exec(str)) !== null) {
if (match.index === pattern.lastIndex) {
pattern.lastIndex++;
}
match[1] = parseInt(match[1]);
if(biggest < match[1]) {
biggest = match[1];
}
}
return biggest;
}