Using regex to extract a double digit number from a string - javascript

I want to extract the "73" from this string:
wiring_details_1-6-73
The numbers 1, 6 and 73 are all vars so I need it to be value independant, I found this website which generated this regex:
.*?\\d+.*?\\d+.*?(\\d+)
But that seems a bit overkill and complicated, what is the cleanest method to extract the "73"?

var string = "wiring_details_1-6-73"
var chunks = string.split("-");
alert(chunks[chunks.length-1]) //73
demo: http://jsfiddle.net/eawBT/

You can use this /\d{1,2}$/
var str = "wiring_details_1-6-73";
var result = str.match(/\d{1,2}$/);
this returns an array with the matched number as string and you can access the value as result[0].

Related

Javascript get value in attribute

I am using jquery .attr in an input type so when I run this
console.log('name: '+$(this).attr('name'));
output is: name: user_project_category[65][skill][9]
How can I get the 65 and 9?
You can use Regular Expressions to extract text from between the brackets into an array and then you can access the array to get the values you want, you can either extract all text between brackets or just the numbers:
var yourInput = "user_project_category[65][skill][9]";
var allMatches = yourInput.match(/\[(.*?)\]/g);
console.log(allMatches[0]);
console.log(allMatches[2]);
var numberMatches = yourInput.match(/\[([0-9]*?)\]/g);
console.log(numberMatches[0]);
console.log(numberMatches[1]);
var data = "name: user_project_category[65][skill][9]";
console.log(data.split("[")[1].slice(0,-1))//use split to get 65] use slice to remove ]
console.log(data.split("[")[3].slice(0,-1))//use split to get 9] use slice to remove ]
You can use split with slice
Assuming this is not dynamic and format is the same.
for dynamic use regex
Use regex.
var output = 'user_project_category[65][skill][9]';
var numbers = output.match(/\d+/g).map(Number);
alert(numbers);
output: 65,9
Do whatever you want to do with number.
working fiddle
Use regular expression or split function in JavaScript
var output= 'user_project_category[65][skill][9]';
output.split(/(\d+)/)[1];
output.split(/(\d+)/)[3];

Substring a part of a string using angularjs

I have a string like this string(1), I want to get substring remove the last part to obtain just string any suggestions please!!
PS.the string could be: sringggg(125).
You can use various options to get the desired string.
//With regular expression with split() and fetch the first element of array
console.log('sringggg(125)'.split(/\(\d+\)/)[0]);
//Using string with split() and fetch the first element of array
console.log('sringggg(125)'.split('(')[0]);
//Using substr and indexOf
var str = 'sringggg(125)'
console.log(str.substr(0, str.indexOf('(')));
References
String.prototype.split()
String.prototype.indexOf()
If string is always in same pattern and ' ( ' is a separator use split .
var string = 'string(1)'
var result = string .split('(')[0];
Try using regexp
var tesst = "string(1)"
var test = tesst.match(/^[^\(]+/);
// test = "string"

Extract Fractional Number From String

I have a string that looks something like this
Hey this is my 1.20 string
I'm trying to just extract 1.20 from it.
What's the best way to do this?
I've tried something like this, but I get the value of 1.20,20 rather than just 1.20
var query = $(".query_time").html();
var matches = query.match(/\d.(\d+)/);
The result of the match function is an array, not a string. So simply take
var nb = query.match(/\d.(\d+)/)[0];
BTW, you should also escape the dot if you want to have more precise match :
var nb = query.match(/\d\.(\d+)/)[0];
or this if you want to accept commas (depends on the language) :
var nb = query.match(/\d[\.,](\d+)/)[0];
But the exact regex will be based on your exact needs, of course and to match any number (scientific notation ?) I'd suggest to have a look at more complex regex.
The value of matches is actually [ "1.20", "20" ] (which is an array). If you print it, it will get converted to a string, hence the 1.20,20.
String.match returns null or an array of matches where the first index is the fully matched part and then whichever parts you wanted. So the value you want is matches[0].
Try the following
var nb = query.match(/\d\.\d+/)[0]; // "1.20"
You need to escape . because that stands for any character.
Remove the capture group (\d+) and the second match is not returned
Add [0] index to retrieve the match

Getting ID from URL using JavaScript

I`m new to JavaScript and I need some help extracting the ID from URL using JavaScript for a gallery.
This is the link: www.shinylook.ro/produs/44/mocasini-barbati.html.
I need that number 44 in a variable.
You have to use the location object to get the URL, after that, you can use split to split the URL on the slashes.
location.pathname.split('/')[2] // Returns 44 in your example
You can do that with String#split or with a regular expression.
String#split lets you split a string on a delimiter and get an array as a result. So in your case, you could split on / and get an array where 44 would be at index 2.
Regular expressions let you do much more complicated matching and extraction, as shown by the various demos on the linked page. For instance,
var str = "www.shinylook.ro/produs/44/mocasini-barbati.html";
var m = /produs\/(\d+)\//.exec(str);
if (m) {
// m[1] has the number (as a string)
}
In both cases, the number will be a string. You can parse it with parseInt, e.g. n = parseInt(s, 10) (assuming it's base 10).

How can I parse a value out of a string with javascript?

I a string name content that has inside the text "data-RowKey=xxx". I am trying to get out xxx so I tried the following:
var val = content.substring(12 + content.indexOf("data-RowKey="), 3);
This does not work at all. rather than just get three characters I get a very long string. Can anyone see what I am doing wrong
You're using wrong tool. When you want to capture a data matching some pattern, you should use regular expressions. If your value is exactly three symbols, correct expression would be /data-RowKey=(...)/ with . standing for any symbol and () specifying part to capture.
.substring() [MDN] takes two indexes, .substr() [MDN] takes an index and the length. Try:
var val = content.substr(12 + content.indexOf("data-RowKey="), 3);
If "data-RowKey=xxx" is the whole string, there are various other ways to get xxx:
var val = content.replace('data-RowKey=', '');
var val = content.split('=')[1]; // assuming `=` does not appear in xxx
This works:
var value = content.match(/data-RowKey=(.*)/)[1];
Live DEMO
If there could be values after the xxx, use this:
"data-RowKey=123abc".match(/data-RowKey=(.{3}).*/)[1] // 123
If your rowkey is numeric, this might be best since you get the number as an integer and wouldn't need to convert later:
var val = parseInt( content.split("data-RowKey=")[1] );
If always the three characters and/or no need to convert:
var val = content.split("data-RowKey=")[1].substring(0,3);

Categories

Resources