Extracting the id in all these cases - javascript

How can I always extract the number 11 in all these cases.
id="section-11"
id="test-11"
id="something-11"
I do $(this).attr('id'); then what do I do next?

Many ways to achieve that, one way is to use .split() like:
var id = "section-11";
var number = id.split(/-/)[ 1 ];
alert( number ); // 11

$(this).attr('id').match(/\d+/)[0]
This will pull the first numeric match.

Assuming that those last two digits are going to be the only numbers in the id, here's a regex replace to do it:
var id = 'something-11';
var num = id.replace(/\D/g,'');
alert(num);
The above deletes all non-numeric characters from the string.
jsfiddle example

var id = parseInt($(this).attr('id).substring($(this).attr('id').lastIndexOf('-')+1));
The .split() example above also works, but you'll need to grab the highest index in the array, in case you name an id with more than 1 dash: sub-section-11

you can split the string to an array by "-", then you will get the id from the second place of the array.

Related

How to remove strings before nth character in a text?

I have a dynamically generated text like this
xxxxxx-xxxx-xxxxx-xxxxx-Map-B-844-0
How can I remove everything before Map ...? I know there is a hard coded way to do this by using substring() but as I said these strings are dynamic and before Map .. can change so I need to do this dynamically by removing everything before 4th index of - character.
You could remove all four minuses and the characters between from start of the string.
var string = 'xxxxxx-xxxx-xxxxx-xxxxx-Map-B-844-0',
stripped = string.replace(/^([^-]*-){4}/, '');
console.log(stripped);
I would just find the index of Map and use it to slice the string:
let str = "xxxxxx-xxxx-xxxxx-xxxxx-Map-B-844-0"
let ind = str.indexOf("Map")
console.log(str.slice(ind))
If you prefer a regex (or you may have occurrences of Map in the prefix) you man match exactly what you want with:
let str = "xxxxxx-xxxx-xxxxx-xxxxx-Map-B-844-0"
let arr = str.match(/^(?:.+?-){4}(.*)/)
console.log(arr[1])
I would just split on the word Map and take the first index
var splitUp = 'xxxxxx-xxxx-xxxxx-xxxxx-Map-B-844-0'.split('Map')
var firstPart = splitUp[0]
Uses String.replace with regex expression should be the popular solution.
Based on the OP states: so I need to do this dynamically by removing everything before 4th index of - character.,
I think another solution is split('-') first, then join the strings after 4th -.
let test = 'xxxxxx-xxxx-xxxxx-xxxxx-Map-B-844-0'
console.log(test.split('-').slice(4).join('-'))

How to get value between 2 character

I have an Id of '2015-11-30_1112_3'. How do I get the values between the two underscores(_) so I am left with '1112'.
Please note that the length of the string varies.
simplest solution would be
var value = '2015-11-30_1112_3';
alert( value.split( "_" )[ 1 ] );
just split the variable, which should give you an array of 3 items. Second item is what you are looking for
You can of course use a regular expression:
s.match(/_(.*)_/)[1]
Explanation: I assume s is your string. The expression matches everything, i.e. (.*), between two underscores. You have to select index 1 of the result because index 0 will give you the complete match including the underscores. Subsequent elements contain the bracketed groups.
You can do this if you are sure that all ids have the same format:
var str= '2015-11-30_1112_3';
var array=str.split("_");
alert(array[1]);
Write like this..
var value = "2015-11-30_1112_3";
var value1 = value.match(/_(.+)_/g);
Demo : Click here
Please try below solution with the help of this solution you can find value between two different symbols as well.
var str = "2015-11-30_1112_3";
var newStr = str.split('_')[1].split('_')[0];
alert(newStr);

JS RegExp matched entries count

Is it possible to get a count of entries that matched of RegExp in JS?
Let's assume an simpliest example:
var pattern =/\bstring\b/g;
var str = "My the best string comes here. Do you want another one? That will be a string too!";
So how to get its count? If I try use a standard method exec():
pattern.exec(str);
...it shows me an array, contains unique matched entry:
["string"]
there is the lenght 1 of this array, but in reality there are 2 points where matched entry was found.
You can achieve using .match() :
var pattern =/\bstring\b/g;
var str = "My the best string comes here. Do you want another one? That will be a string too!";
alert(str.match(pattern).length);
Demo Fiddle

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

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