-
Jan 28th, 2021, 11:07 AM
#1
Thread Starter
New Member
[RESOLVED] Trying to get SUBSTRING
I have a label control with text Present: 1/1(2%)
I want to change via script to Present 1(2%)
When testing, I can get the string Present: 1 but I can't get the other half (2%) .
What am I missing?
Code:
<script>
//var x = document.getElementById("Label1");
//document.getElementById("Label1").innerHTML = x.innerHTML.substring(0, 6);
var y = document.getElementById("Label2");
var nStart = y.innerHTML.indexOf("/")
var nEnd = y.innerHTML.indexOf("(")
document.getElementById("Label2").innerHTML = y.innerHTML.substring(0, nStart);
document.getElementById("Label2").innerHTML = y.innerHTML.substring(nEnd,5);
document.getElementById("Label2").innerHTML = y.innerHTML.substring(0, nStart) + y.innerHTML.substring(nEnd,5)
</script>
document.getElementById("Label2").innerHTML = y.innerHTML.substring(0, nStart); <--- Gives me Present: 1
document.getElementById("Label2").innerHTML = y.innerHTML.substring(nEnd,5); <--- Gives me nt: 1/1
document.getElementById("Label2").innerHTML = y.innerHTML.substring(0, nStart) + y.innerHTML.substring(nEnd,5) <-- Gives me Present: 1nt: 1/1
-
Jan 28th, 2021, 12:43 PM
#2
Re: Trying to get SUBSTRING
Are you able to edit the DOM? String manipulation is usually messy.. if you ever change it from "Present" to "Hello" or anything else, or change the formatting, your code would break.
Typically you would wrap the percent in a span. And access it by ID or by class
IE)
Code:
<label>
Present:
<span id="current">
1
</span>
<span id="outof">
/
<span id="total">
1
</span>
</span>
</label>
And then you can just manipulate either the total by accessing
document.getElementById("total")
or can manipulate the entire "/1" with document.getElementById("outof")
-
Feb 2nd, 2021, 03:22 PM
#3
Re: Trying to get SUBSTRING
You could use regular expressions in this case:
Code:
window.onload = function() {
document.getElementById('changeLabel2').onclick = changeLabel2_Click;
}
changeLabel2_Click = function() {
const label2 = document.getElementById('Label2');
const text = label2.innerHTML;
const pattern = /(?<name>\w+):\s?(?<number>\d)\/\d(?<percent>\(\d%\))/g
const { groups: { name, number, percent } } = pattern.exec(text);
label2.innerHTML = `${name}: ${number}${percent}`;
}
Fiddle: https://jsfiddle.net/3ruz5whs/
-
Feb 3rd, 2021, 12:16 PM
#4
Thread Starter
New Member
Re: Trying to get SUBSTRING
Thanks all.
Someone pointed out to me that on a .substring(x,y), x and y are indices so they would get swapped on who has a higher index value. I ended up using below recommendation:
Code:
document.getElementById("Label2").innerHTML = document.getElementById("Label2").innerHTML.replace(/\/\d*/,"")
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|