How would I capture the all the numbers after the semi colon: in this code?
Ignore this rgFHTeVZ-4444322794 , it only appears because I'm working on a preview link.
<p id="productName">rgFHTeVZ-4444322794Diecut model number: 110</p>
the productName is dynamically added from the URL parameter in this script below:
<script type='text/javascript'>
// start by creating a function
function loadUp(){
var str = decodeURIComponent(window.location.search.replace(/(?:(\D+=))/ig, "")) //get the search parameters from the url and remove everything before the "=" sign
document.getElementById('productName').innerHTML = str //assign that string to the "innerHTML" of the h1 tag that has an id of "productName"
};
window.onload = loadUp; // once the page has loaded, fire off that function
</script>
I want to take those numbers and use them to dynamically add to a img src attribute so the image would change based on the parameter.
The 110 is what I would like to dynamically change.
the img src looks like this: https://cdn2.hubspot.net/hubf/43534/asset-diecut/sampleImage/110_a.png
any help would be appreciated, thank you
1) get contents of div as string
2) split string into array broken on :
3) assign div new innerHTML
let text = document.getElementById('productName').innerHTML let textArray = text.split(': ') document.getElementById('productName').innerHTML = (textArray[1]).trim()
<p id="productName">rgFHTeVZ-4444322794Diecut model number: 110</p>
You can use split(":") to convert it to an array:
Array ["Diecut model number", " 110"]
Then simply pick index 1.
document.getElementById('productName').innerHTML = str.split(":")[1];
*you can use trim() to remove white-spaces
str.split(":")[1].trim()
Here is another approach you can use for this.
You can always use RegEx for this scenario as long as its always on the last digits
let array = document.getElementById('productName').innerHTML; let output = document.getElementById('output'); let num = array.match(/\d+$/g); // or if combination of Letter or number => (/\w+$/g); output.innerHTML = num[0];
<p id="productName">rgFHTeVZ-4444322794Diecut model number: 110</p> <div id="output"></div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.