Finding a numeric ID within an URL including numbers - javascript

I've run into some problems accessing and forwarding an ID.
I successfully extracted the ID from my URL but I run into problems if the URL contains unpredictable numbers aswell.
To clear things up a bit:
My efforts to extract the ID so far (JS)
var idString = window.location.href;
idString = idString.replace(/e107/gi, "__ersetzt__");
idString = idString.replace("http://localhost/Westbomke/backendV5/", "");
idString = idString.replace(/[^0-9]+/g, "");
Some URL examples
Working:
http://localhost/Westbomke/backendV5/e107-master/e107_projekte/BMW/235_Projekt_BMW-Event/page.php Result: 235 = id
Not working:
localhost/Westbomke/backendV5/e107-master/e107_projekte/BMW/235_Projekt_BMW-Event01/page.php
localhost/Westbomke/backendV5/e107-master/e107_projekte/company1337/235_Projekt_1337Event/page.php
now if I could exclude the /******_Projekt_ Part (**** = random amount of numbers) and parse it into an Integer I would be fine, but I dont know how to do this or if it's possible.
I tried to find something on here and via google but I most likely dont ask for the right stuff.
Thanks for your time and help in advance!

You can try with:
var url = 'http://localhost/Westbomke/backendV5/e107-master/e107_projekte/BMW/235_Projekt_BMW-Event/page.php';
var id = +url.match(/\/(\d+)/)[1];

Is this URL you are working on stable in terms of structure?
If you are nto familiar with Regular Expressions and the Structure is pretty stable , then the following code will do the job for you:
var myString = "http://localhost/Westbomke/backendV5/e107-master/e107_projekte/BMW/235_Projekt_BMW-Event/page.php";
var mySplitString = myString.split("/");
var myNumber = parseInt(mySplitString[8]);
console.log(myNumber);
Adding the below Function which will provide you with a bit more flexibility.
var myString = "http://localhost/Westbomke/backendV5/e107-master/e107_projekte/BMW/235_Projekt_BMW-Event/page.php";
function getProject(myString , myDist){
var mySplitString = myString.split("/");
var myID = '';
mySplitString.forEach(function(key , index){
if(key.indexOf(myDist) > 0)
myID = parseInt(mySplitString[index]);
});
return myID;
}
var myID = getProject(myString , "Projekt");
console.log(myID);

Related

JavaScript Replace Text with Image

I'm still newbie, I want to replace all 'Snowman' text in the string chain for images of snowman.
Is there any easy possibility to do this in only JS?
Ok I forgot this is important too. It gets string chains actually from my Twitch channel chat to my local server using websocket node.js. When someone comment on the Twitch channel it goes into my local server in the string chain format. What I want to do is to replace or change the comment like Snowman to actual Image of Snowman.
I have very low experience with the DOM and jQuery but if this would help I can try.
Code:
Analyzing the twitch chat:
wsTwitch.onmessage = function(event) {
let eventData = JSON.parse(event.data);
Replacing text with image:
eventData2 = eventData.text.replace(/Snowman/gi, "img src='snowman.png'");
You can try like below
eventData2 = eventData.text.replace(/Snowman/gi, "<img src='path/snowman.png' />");
This will might help you.
Try this way.
var txtArr = eventData.text.split(' ');
for(var i = 0; i < txtArr.length; i++){
if(txtArr[i] === "Snowman")
txtArr[i] = `<img src="url">`;
}
var newTxt = txtArr.join(' ');
document.getElementById("txt").innerHTML = newTxt; //replace with existing element

Formating data pulled from the url

I currently have a script that pulls a parameter from the url and displays on the page. My problem is that I need to format the decimal place for the value.
UPDATED (This is working now. Thank you all.)
Code
$(document).ready(function () {
var url = $.url('https://www.google.com/blah/blahblah/index.htm?x=50.5200');
var x = url.param('x');
var x2 = parseFloat(x).toFixed(2);
$("#value").text(x2);
});
Try this:
var decimal = '50.5230';
var num = parseFloat(decimal).toFixed(2);
console.log(num);

jQuery get last part of URL

I have a series of pages where I need to get a specific code for a button.
I want to put the code which is in the url into a variable with jQuery.
An example URL is www.example.com/folder/code/12345/
I want to get the number part in a variable called (siteCode)
Thanks in advance for any answers.
jquery / Pseudo code:
var siteCode;
// start function
function imageCode(){
siteCode // equals number part of URL
$('.button').attr('src', 'http:www.example.com/images/'+siteCode+'.jpg');
}
You can use the following code to get the last part of the url.:
var value = url.substring(url.lastIndexOf('/') + 1);
I'd suggest:
var URI = 'www.example.com/folder/code/12345/',
parts = URI.split('/'),
lastPart = parts.pop() == '' ? parts[parts.length - 1] : parts.pop();
JS Fiddle demo.
var str="url";
str.split("/")[3]
you can use split
There is one best way to take last part of URL is like following which generally has been used in real implementation.
There are Some loopholes in previously given answer was:
1.Consider what if there is a url like www.example.com/folder/code/12345 (Without '/' forward slash) Than none of the above code will work as per expectation.
2.Consider if folder hierarchy increases like www.example.com/folder/sub-folder/sub-sub-folder/code/12345
$(function () {
siteCode = getLastPartOfUrl('www.example.com/folder/code/12345/');
});
var getLastPartOfUrl =function($url) {
var url = $url;
var urlsplit = url.split("/");
var lastpart = urlsplit[urlsplit.length-1];
if(lastpart==='')
{
lastpart = urlsplit[urlsplit.length-2];
}
return lastpart;
}
Also try using regex
var url = "www.example.com/folder/code/12345";
var checkExt = /\d$/i.test(url);
if (checkExt) {
alert("Yup its a numeric");
} else {
alert("Nope");
}

Javascript REGEX: need to retrieve the ID as well as start and end time from embed URL

Here is an example of url structure I'll be working with (ignore the age of electric video :) )
http://www.youtube.com/embed/ABCumLrphFA?&start=20&end=50
Basically I want to be able to grab the video id, the chosen start time (20) and end chosen time (50) and save them as variables from any URL that follows the pattern above.
So a simple setup is this:
var url = 'http://www.youtube.com/embed/ABCumLrphFA?&start=20&end=50'
// get youtube id
function youtubeid(url) {
var ytid = url.match(dont know);
ytid = ytid[1];
return ytid;
}
// get youtube start time
function youtubeStart(url) {
var ytStart = url.match(dont know);
ytStart=ytStart[1];
return ytStart;
}
// get youtube end time
function youtubeEnd(url) {
var ytEnd = url.match(dont know);
ytEnd=ytEnd[1];
return ytEnd;
}
If you could help me fill in the blanks that would be most amazing. I've been staring at regex documentation for a while now and just getting more and more confused.
This other Stack Overflow answer may help you. I used Peter Mortensen's answer below.
Get query string values in JavaScript
To obtain the actual YouTube Id, you can use this regular expression:
http:\/\/www.youtube.com\/embed\/(.{11})
That regex will return the value in parenthesis. You can test it here:
http://www.pagecolumn.com/tool/regtest.htm
Sample code:
var url = 'http://www.youtube.com/embed/ABCumLrphFA?&start=20&end=50'
// get youtube id
function youtubeid(url) {
var ytid = url.match(/http:\/\/www.youtube.com\/embed\/(.{11})/);
ytid = ytid[1];
return ytid;
}
alert(youtubeid(url));
function getParameterByName(name, url) {
var match = RegExp('[?&]' + name + '=([^&]*)')
.exec(url);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
alert(getParameterByName('start', url));
alert(getParameterByName('end', url));
1
/http:\/\/www\.youtube\.com\/embed\/([^?]+)/
2
/http:\/\/www\.youtube\.com\/embed\/[^?]+.*[?&]start=(\d+)(?:&|$)/
3
/http:\/\/www\.youtube\.com\/embed\/[^?]+.*[?&]end=(\d+)(?:&|$)/
This'll only work if you know your URLs will look exactly like the one you gave (no extra query parameters; start and end always in that order; no HTTPS; etc.). But you can get them all at once:
js> str = 'http://www.youtube.com/embed/ABCumLrphFA?&start=20&end=50'
http://www.youtube.com/embed/ABCumLrphFA?&start=20&end=50
js> rxp = /http:\/\/www.youtube.com\/embed\/(.*)\?&start=(\d+)?&end=(\d+)?/
/http:\/\/www.youtube.com\/embed\/(.*)\?&start=(\d+)?&end=(\d+)?/
js> result = rxp.exec(str)
http://www.youtube.com/embed/ABCumLrphFA?&start=20&end=50,ABCumLrphFA,20,50
js> result[0]
http://www.youtube.com/embed/ABCumLrphFA?&start=20&end=50
js> result[1]
ABCumLrphFA
js> result[2]
20
js> result[3]
50
I believe it's possible to write a regex that can cope with all the quirks I mentioned above, but it's way uglier and makes it harder to understand. Anyway - hope this helps!
See also: JavaScript Regex Escape Sequences and JavaScript Regex Methods
var url = "http://www.youtube.com/embed/ABCumLrphFA?&start=20&end=50";
// get youtube id
function youtubeid(url) {
q = url.substring(url.lastIndexOf("/")+1);
var ytid = q.substring(q.lastIndexOf("?"), -1);
return ytid;
}
// get youtube start time
function youtubeStart(url) {
q = url.substring(url.lastIndexOf("/")+1);
var ytStart = q.substring(q.indexOf("&start")+7,q.indexOf("&end"));
return ytStart;
}
// get youtube end time
function youtubeEnd(url) {
q = url.substring(url.lastIndexOf("/")+1);
var ytEnd = q.substring(q.indexOf("&end")+5);
return ytEnd;
}
console.log(youtubeid(url));
console.log(youtubeStart(url));
console.log(youtubeEnd(url));
To retrieve the id
url.match(/embed\/(.*)\?/)
The best way to retrieve URL params (start and end) is to do something like Get Querystring with Dojo Then you could use the following to retrieve start and end
var qs = getUrlParams();
console.log("start is " + qs.start + " and end is " + qs.end )

Javascript RegEx Mysteries (for a poor C programmer)

This is clearly a RTFM issue, but after I did so repeatedly I just can't get the damn thing to work so there are times when asking for help makes sense:
var text = "KEY:01 VAL:1.10,KEY:02 VAL:2.20,KEY:03 VAL:3.30";
var pattern = '/KEY:(\S+) VAL:([^,]+)/g';
//var pattern = '/KEY:(\S+) VAL:(.?+)(?:(?=,KEY:)|$)/g';
//var pattern = '/KEY:(\S+) VAL:(.+)$/g';
//pattern.compile(pattern);
var kv = null;
var row = 0, col = 0;
while((kv = pattern.exec(text) != null))
{
row = kv[1].charAt(0) - '0';
col = kv[1].charAt(1) - '0';
e = document.getElementById('live').rows[row].cells;
e[col].innerHTML = kv[2].slice(0, kv[2].indexOf(","));
}
kv[1] is supposed to give "01"
kv[2] is supposed to give "1.10"
...and of course kv[] should list all the values of 'text'
to fill the table called 'live'.
But I can't get to have pattern.exec() succeed in doing that.
Where is the glitch?
First, the delimiters for the RegExp should be /s, there's no need to put them in ' delimiters. i.e. to get your exec to run properly you should have:
var pattern = /KEY:(\S+) VAL:([^,]+)/g;
Second, you're assigning a boolean to kv which you don't want. The while will obviously only evaluate to true if it's not null so that's redundant. Instead you just need:
while (kv = pattern.exec(text)) {
That should get your code to work as you desire.
the syntax for pattern objects doesn't include quoting, such as:
var pattern=/KEY:(\S+) VAL:([^,]+)/g;
http://www.w3schools.com/jsref/jsref_regexp_exec.asp
It should be
var pattern = /KEY:(\S+) VAL:([^,]+)/g;
http://www.regular-expressions.info/ is a good place to start with.

Categories

Resources