var name = $(".column_nr_matching:last").attr("name");
// this gives me col_nr359
and here I add plus 1
var added_one = name + (+1);
When I look with console it gives me this:
col_nr3591
I need it to be
col_nr360
var name = $(".column_nr_matching:last").attr("name");
// this gives me col_nr359
and here I add plus 1
var added_one = name + (+1);
When I look with console it gives me this:
col_nr3591
I need it to be
col_nr360
Because col_nr359
is a string, and by using +
, you are concatenating 1
to that string. You need to do something like this:
document.getElementById('increment').onclick = function (){
//get the innertext from the span
var text = document.getElementById('colid').innerText;
//replace the 'col_nr' text with empty string to get the number
var nr = text.replace('col_nr','');
//parses the number to int and sums 1, then concatenate back
var new_id = 'col_nr' + (parseInt(nr) + 1);
//set the new text to the span
document.getElementById('colid').innerText = new_id;
}
<span id="colid">col_nr359</span>
<br>
<button id="increment" > Increment </button>
As mentioned, name
is a string, not a number. You need to just get the number part so you can add one to it. One possible way of doing so is with a regex string replace, where you use capture group to get the number part, and replace it with that number plus one. Example:
const name = "col_nr359";
const added_one = name.replace(/(\d*)$/, m => String(+m + 1))
console.log(added_one)
col_nr359
is a String
, even JavaScript can't interpret it as number
, since there are characters in front.
What you have to do is split the string so you have col_nr and 359, then add 1 to the 359, then concatenate it again.
You are mixing datatypes. col_nrxxx is a string and will always be one. You have to cut out the 359, then parse it to int, then add the +1, then concat it back to the string.