In C# I can do this
string ID = "ContentPlaceHolderDefault_MainSiteSectionArea_MyPagePlaceHolder_Item4_FavoritAmusementCalender_6_deleteRight_2";
ID = ID.Substring(ID.LastIndexOf("_") + 1);
to return the last int 2
How can I most easily do this in jQuery/JavaScript
The id is created dynamic and can for now be up to 3 digit.
Thanks in advance.
You were close -- just case sensitive:
ID = ID.substring(ID.lastIndexOf("_") + 1);
JS Fiddle Example
JavaScript also has a lastIndexOf() method, see here. You can therefore use:
var str1 = "Blah, blah, blah Calender_6_deleteRight_272";
var str2 = str1.substr (str1.lastIndexOf ("_") + 1);
This gives you 272.
Keep in mind that, if the string doesn't contain an underscore, you'll get the original string back in its entirety. That may or may not be desired in your specific case - you can check the result of the lastIndexOf() call against -1 to detect this.
Have you tried str.substr(-1)?
You should do this with:
function get_last_part(str){
var split = str.split('_');
return split[split.length-1];
}
console.log(get_last_part("ContentPlaceHolderDefault_MainSiteSectionArea_MyPagePlaceHolder_Item4_FavoritAmusementCalender_6_deleteRight_2")); // this will write "2" in console
In this way you will get always result and you don't need to concern about out of index problems. This will return always last part of your string, if it doesn't have _ you will get first part of it.
console.log(get_last_part("Content")); // will write "Content" into console
Related
The expression str.substring(0, str.indexOf("begin:")).trim() gets me the string before begin: but if I want the string that comes after begin:, what do I do?
Or use the same substring function but use the length as the first parameter (factoring in the length of "begin:") and nothing for the second:
str.substring(str.indexOf("begin:")+6).trim()
As the docs for substring state: "If indexEnd is omitted, substring() extracts characters to the end of the string."
just split the string at begin: and get the next portion:
var strPortion=str.split("begin:");
var desiredString=strPortion[1].trim();
so if the string is: "Now we begin: it is better to try splitting the string";
the above code will give "it is better to try splitting the string";
Not completely sure, but try:
str.substring(str.indexOf("begin:"),str.length).trim()
I'm not sure if you want 'begin' included or discarded.
var needle = "begin:";
var haystack = "begin: This is a story all about how my life got flipped turned upside down";
var phrase = str.substring(str.indexOf(needle) + needle.length).trim();
That will give you what you are looking for. I only am posting the answer due to others comments of the ambiguity and modulation of the code. So yeah.
Check it out and change the needle if you'd like. Code example shows how to get before the needle as well. https://jsfiddle.net/jL6zxcu3/1/
var needle = "begin:"
str.substring(str.indexOf(needle)+ needle.length, str.length).trim()
Or
var needle = "begin:"
str.substring(str.indexOf(needle)+ needle.length).trim()
The second Paramter is not needed if you want search to the end of string
Given the circumstances I have to use a node list to get at elements that I need to work with. I am able to use .textContent (or .nodeValue) to return a string that I need, but I am having trouble finding a way to get that string into any type of number. I need to have it in number form so I can perform calculations with it. I have tried Number(), parseInt(), etc. All return NaN. I am pretty new to JS so hopefully this is an easy issue to solve.
var siteActual = tdNodeListActual[36].textContent; // location of data
console.log(siteActual); // returns the value 1 as it should
var asd = Number(siteActual); // test variable to convert string to number
console.log(asd); // returns NaN
EDIT: I checked .length as one of you suggested and it was 2, so those saying it may be an invisible character are probably right. I am trying to make changes to a SharePoint page, that is why I am not familiar with what the markup is. Any suggestions on how to remove all but the number would be helpful.
Your code should work as-is if the content is really just 1 (as should parseInt). So there must be something other than valid numbers in your content.
Sometimes there can be content that you can't see, e.g. in the example below the second td contains an invisible "zero-width space" character.
var tdNodeListActual = document.querySelectorAll("td");
var good = tdNodeListActual[0].textContent;
var bad = tdNodeListActual[1].textContent;
alert(good + "==" + Number(good) + ", but " + bad + "==" + Number(bad))
<table><tr>
<td>1</td>
<td>2</td>
</tr></table>
You can remove all non-digit characters (except . and ,) using a regex, e.g.:
siteActual = siteActual.replace(/[^\d.,]/g, '');
Using parseInt(...)
Sample:
var siteActual = tdNodeListActual[36].textContent; // location of data
console.log(siteActual); // returns the value 1 as it should
var asd = Number(parseInt(siteActual)); // test variable to convert string to number
console.log(asd); // should return 1
i want to remove comma from a number (e.g change 1,125 to 1125 ) in a .tpl file.
The value comes dynamically like ${variableMap[key]}
var a='1,125';
a=a.replace(/\,/g,''); // 1125, but a string, so convert it to number
a=parseInt(a,10);
Hope it helps.
var a='1,125'
a=a.replace(/\,/g,'')
a=Number(a)
You can use the below function. This function can also handle larger numbers like 123,123,123.
function removeCommas(str) {
while (str.search(",") >= 0) {
str = (str + "").replace(',', '');
}
return str;
};
var s = '1,125';
s = s.split(',').join('');
Hope that helps.
✨ ES2021 ✨ added replaceAll, so no need for regular expression:
const str = '1,125,100.05';
const number = parseFloat(str.replaceAll(",", ""));
You can use Regular Expression to change as it is faster than split join
var s = '1,125';
s = s.replace(/,/g, '');
//output 1125
Incoming value may not always be a string. If the incoming value is a numeric the replace method won't be available and you'll get an error.
Suggest using isNaN to see if numeric, then assume string and do replacement otherwise.
if(isNaN(x)) {
x = parseInt(x.replace(/[,]/g,''));
}
(Not foolproof because 'not number' doesn't prove it is a string, but unless you're doing something very weird should be good enough).
You can also add other symbols to the character group to remove other stray chars (such as currency symbols).
Suppose this is my code
var str="abc=1234587;abc=19855284;abc=1234587;abc=19855284;abc=1234587;abc=19855284;abc=1234587;abc=19855284;abc=1234587;abc=19855284;abc=1234587;abc=19855284;abc=1234587;abc=19855284;abc=1234587;abc=19855284;abc=1234587;abc=19855284;abc=1234587;abc=19855284;";
var patt1=/abc=([\d]+)/g;
document.write(str.match(patt1));
i want the output as 1234587,19855284
this doesnt return the number but instead returns the complete string which is in the pattern
if i remove 'g' from the pattern it returns abcd=1234578,1234578 what am i doing wrong??
match() returns an array. The first entry (index 0) is always the matching string. Following that you get the matching group(s).
The toString()-logic of an array takes all elements and joins them with ", ". You can use e.g. join("-") to change that.
Try following code.
var str = "abc=1234587;abc=19855284;abc=1234587;abc=19855284;abc=1234587;abc=19855284;abc=1234587;abc=19855284;abc=1234587;abc=19855284;abc=1234587;abc=19855284;abc=1234587;abc=19855284;abc=1234587;abc=19855284;abc=1234587;abc=19855284;abc=1234587;abc=19855284;";
str = str.replace(/abc=/gi, '');
document.write(str);
If this is what you want
1234587,19855284,1234587,19855284,1234587,19855284,1234587,19855284,1234587,19855284,1234587,19855284,1234587,19855284,1234587,19855284,1234587,19855284,1234587,19855284
then try this
var str="abc=1234587;abc=19855284;abc=1234587;abc=19855284;abc=1234587;abc=19855284;abc=1234587;abc=19855284;abc=1234587;abc=19855284;abc=1234587;abc=19855284;abc=1234587;abc=19855284;abc=1234587;abc=19855284;abc=1234587;abc=19855284;abc=1234587;abc=19855284;";
var patt1=/([\d]+)/g;
document.write(str.match(patt1));
or you can use the array index as sjngm mentioned
I have a string that look something like
something30-mr200
I would like to get everything after the mr (basically the # followed by mr) *always there is going to be the -mr
Any help will be appreciate it.
You can use a regexp like the one Bart gave you, but I suggest using match rather than replace, since in case a match is not found, the result is the entire string when using replace, while null when using match, which seems more logical. (as a general though).
Something like this would do the trick:
function getNumber(string) {
var matches = string.match(/-mr([0-9]+)/);
return matches[1];
}
console.log(getNumber("something30-mr200"));
var result = "something30-mr200".split("mr")[1];
or
var result = "something30-mr200".match(/mr(.*)/)[1];
Why not simply:
-mr(\d+)
Then getting the contents of the capture group?
What about:
function getNumber(input) { // rename with a meaningful name
var match = input.match(/^.*-mr(\d+)$/);
if (match) { // check if the input string matched the pattern
return match[1]; // get the capturing group
}
}
getNumber("something30-mr200"); // "200"
This may work for you:
// Perform the reg exp test
new RegExp(".*-mr(\d+)").test("something30-mr200");
// result will equal the value of the first subexpression
var result = RegExp.$1;
What about finding the position of -mr, then get the substring from there + 3?
It's not regex, but seems to work given your description?