I need to test for "[any number]" in a string in javascript. how would i match it?
Oh, "[" and "]" also need to be matched.
so string like "[1]" or "[12345]" is a match.
Non match: "[23432" or "1]"
So for example:
$('.form .section .parent').find('input.text').each(function(index){
$(this).attr("name", $(this).attr("name").replace("[current]", "['"+index+"']"));
});
I need to replace input fields name: "items[0].firstname" to "items[1].firstname" thanks
This question is related to
javascript
jquery
regex
You can use the following function to find the biggest [number]
in any string.
It returns the value of the biggest [number]
as an Integer.
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;
}
The following demo calculates the biggest number in your textarea every time you click the button.
It allows you to play around with the textarea and re-test the function with a different text.
var biggestNumber = function(str) {_x000D_
var pattern = /\[([0-9]+)\]/g, match, biggest = 0;_x000D_
_x000D_
while ((match = pattern.exec(str)) !== null) {_x000D_
if (match.index === pattern.lastIndex) {_x000D_
pattern.lastIndex++;_x000D_
}_x000D_
match[1] = parseInt(match[1]);_x000D_
if(biggest < match[1]) {_x000D_
biggest = match[1];_x000D_
}_x000D_
}_x000D_
return biggest;_x000D_
}_x000D_
_x000D_
document.getElementById("myButton").addEventListener("click", function() {_x000D_
alert(biggestNumber(document.getElementById("myTextArea").value));_x000D_
});
_x000D_
<div>_x000D_
<textarea rows="6" cols="50" id="myTextArea">_x000D_
this is a test [1] also this [2] is a test_x000D_
and again [18] this is a test. _x000D_
items[14].items[29].firstname too is a test!_x000D_
items[4].firstname too is a test!_x000D_
</textarea>_x000D_
</div>_x000D_
_x000D_
<div>_x000D_
<button id="myButton">Try me</button>_x000D_
</div>
_x000D_
See also this Fiddle!
if("123".search(/^\d+$/) >= 0){
// its a number
}
var mask = /^\d+$/;
if ( myString.exec(mask) ){
/* That's a number */
}
Source: Stackoverflow.com