Javascript: Trouble Converting String to Number - javascript

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

Related

How to Match Multi-Digit Regex In Javascript Using the Star

I am trying to extract a multi-digit number which is preceeded by a non-digit from a string in javascript, but having trouble. For example, I want to get the "32" out of "B32 is the floor".
var str = "B23 is the floor."
var num = str.match(/\d*/);
$("#result").append(Object.prototype.toString.call(num) + ', ');
$("#result").append(Object.prototype.toString.call(num[0]) + ', ');
$("#result").append(num[0] + ', ');
$("#result").append(num[0].length);
Returns:
Result:[object Array], [object String], , 0
num[0] seems to be an empty string.
For some reason the regext /\d*/ does not work the way it is supposed to. I have tried /(\d)/, /(\d)*/, /[0-9]/, and some other reasonable and unreasonable things, but it just doesn't seem to work.
Here is my jsFiddle if you want to take a look:
http://jsfiddle.net/PLYHF/3/
The problem is that the regex parser is "lazy". It sees that your regex is perfectly fine with "nothing" (since * means 0 or more), so anything will pass.
Instead, try /\d+/. This will force there to be at least one digit.
parseInt(/[A-Z]+([0-9]+)/.exec('B23 is the floor.')[1]); // 23
What you'll want to do is match for /^0-9/, and then get the second value (Array[1]) from the returned array. That will contain what's captured by the first group. It would end up looking like this:
var str = "B23 is the floor."
var num = str.match(/[^0-9\s]([0-9]+)/);
$('#result').append(num[1]);
demo

JavaScript lastIndexOf()

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

String manipulation in javascript (remove leading zero & specific character)

var patt = path.match(/P[0-9][0-9][0-9]/);
patt = patt.substr(1); //Remove P
while(patt.charAt(0) === '0') { //Remove 0
patt = patt.substr(1);
}
alert(patt);
patt is fixed to this format:
eg. P001 to P999
What I would like to do is very basic, just remove P and the leading 0 (if any). However, the code above is not working. Thanks for helping
Please use it like this:
var str = patt.join('');
str = str.replace(/P0*/, '');
If the input to this function is guaranteed to be valid (i.e. of the form P001...P999), then you can simply use the following to extract the integer:
parseInt(path.substr(1), 10)
This seems the perfect use case for the global parseInt function.
parseInt(patt.substr(1), 10);
It takes as input the string you want to parse, and the base.
The base is optional, but most people suggest to always explicitly set the base to avoid surprises which may happen in some edge case.
It stops to parse the string as soon as it encounters a not numerical value (blank spaces excluded).
For this reason in the snippet above we're a passing the input string stripped of the first character, that as you've mentioned, is the letter "P".
Also, ES2015 introduced a parseInt function, as static method on the Number constructor.
Just a single line and you get what you want
var path = "P001"; //your code from P001 - P999
solution to remove P and the leading "0" .
parseInt(path.substr(1), 10);
Thanks and Regards

javascript regex to extract the first character after the last specified character

I am trying to extract the first character after the last underscore in a string with an unknown number of '_' in the string but in my case there will always be one, because I added it in another step of the process.
What I tried is this. I also tried the regex by itself to extract from the name, but my result was empty.
var s = "XXXX-XXXX_XX_DigitalF.pdf"
var string = match(/[^_]*$/)[1]
string.charAt(0)
So the final desired result is 'D'. If the RegEx can only get me what is behind the last '_' that is fine because I know I can use the charAt like currently shown. However, if the regex can do the whole thing, even better.
If you know there will always be at least one underscore you can do this:
var s = "XXXX-XXXX_XX_DigitalF.pdf"
var firstCharAfterUnderscore = s.charAt(s.lastIndexOf("_") + 1);
// OR, with regex
var firstCharAfterUnderscore = s.match(/_([^_])[^_]*$/)[1]
With the regex, you can extract just the one letter by using parentheses to capture that part of the match. But I think the .lastIndexOf() version is easier to read.
Either way if there's a possibility of no underscores in the input you'd need to add some additional logic.

Find longest repeating substring in JavaScript using regular expressions

I'd like to find the longest repeating string within a string, implemented in JavaScript and using a regular-expression based approach.
I have an PHP implementation that, when directly ported to JavaScript, doesn't work.
The PHP implementation is taken from an answer to the question "Find longest repeating strings?":
preg_match_all('/(?=((.+)(?:.*?\2)+))/s', $input, $matches, PREG_SET_ORDER);
This will populate $matches[0][X] (where X is the length of $matches[0]) with the longest repeating substring to be found in $input. I have tested this with many input strings and found am confident the output is correct.
The closest direct port in JavaScript is:
var matches = /(?=((.+)(?:.*?\2)+))/.exec(input);
This doesn't give correct results
input Excepted result matches[0][X]
======================================================
inputinput input input
7inputinput input input
inputinput7 input input
7inputinput7 input 7
XXinputinputYY input XX
I'm not familiar enough with regular expressions to understand what the regular expression used here is doing.
There are certainly algorithms I could implement to find the longest repeating substring. Before I attempt to do that, I'm hoping a different regular expression will produce the correct results in JavaScript.
Can the above regular expression be modified such that the expected output is returned in JavaScript? I accept that this may not be possible in a one-liner.
Javascript matches only return the first match -- you have to loop in order to find multiple results. A little testing shows this gets the expected results:
function maxRepeat(input) {
var reg = /(?=((.+)(?:.*?\2)+))/g;
var sub = ""; //somewhere to stick temp results
var maxstr = ""; // our maximum length repeated string
reg.lastIndex = 0; // because reg previously existed, we may need to reset this
sub = reg.exec(input); // find the first repeated string
while (!(sub == null)){
if ((!(sub == null)) && (sub[2].length > maxstr.length)){
maxstr = sub[2];
}
sub = reg.exec(input);
reg.lastIndex++; // start searching from the next position
}
return maxstr;
}
// I'm logging to console for convenience
console.log(maxRepeat("aabcd")); //aa
console.log(maxRepeat("inputinput")); //input
console.log(maxRepeat("7inputinput")); //input
console.log(maxRepeat("inputinput7")); //input
console.log(maxRepeat("7inputinput7")); //input
console.log(maxRepeat("xxabcdyy")); //x
console.log(maxRepeat("XXinputinputYY")); //input
Note that for "xxabcdyy" you only get "x" back, as it returns the first string of maximum length.
It seems JS regexes are a bit weird. I don't have a complete answer, but here's what I found.
Although I thought they did the same thing re.exec() and "string".match(re) behave differently. Exec seems to only return the first match it finds, whereas match seems to return all of them (using /g in both cases).
On the other hand, exec seems to work correctly with ?= in the regex whereas match returns all empty strings. Removing the ?= leaves us with
re = /((.+)(?:.*?\2)+)/g
Using that
"XXinputinputYY".match(re);
returns
["XX", "inputinput", "YY"]
whereas
re.exec("XXinputinputYY");
returns
["XX", "XX", "X"]
So at least with match you get inputinput as one of your values. Obviously, this neither pulls out the longest, nor removes the redundancy, but maybe it helps nonetheless.
One other thing, I tested in firebug's console which threw an error about not supporting $1, so maybe there's something in the $ vars worth looking at.

Categories

Resources