Proper Use Of YouTube Url Regex - javascript

I found this regex on stack overflow to get the youtube video id.
function ytVidId(youtubeurl) {
var p = /^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;
return (url.match(p)) ? RegExp.$1 : false;
}
I feel like I'm missing something very obvious, but I just don't understand how to actually use it. How do I get this to affect my text input field named "youtubeurl" before it's prepared for the database?
Thanks a lot... Any help appreciated!

First you need to get the text from the textbox, perhaps with document.getelementbyid().value, then you could do (e.g if your textbox's id is #txt1 you can use this code:
function ytVidId(youtubeurl) {
var p = /^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;
return (url.match(p)) ? RegExp.$1 : false;
}
var ytURL = document.getelementbyid("txt1").value;
var ytID = ytVidID(ytURL);
now the variable ytID contains the youtube video ID and you can add it to the database how you want

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

Finding a numeric ID within an URL including numbers

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);

Getting JQuery from given HTML text?

I got a question while I parse html using JQuery.
Let me have a simple example for my question.
As you might definitely know, when I need to parse ...
<li class="info"> hello </li>
I get text by
$(".info").text()
my question is.. for given full html and token of text ,can I find query string ?
in case of above example, what I want to get is.
var queryStr = findQuery(html,"hello") // queryStr = '.info'
I know there might be more than one result and there would be various type of expression according to DOM hierarchy.
So.. generally... If some text (in this example, 'hello' ) is unique in the whole HTML, I might guess there must be a unique and shortest 'query' string which satisfies $(query).text() = "hello"
My question is.. If my guess is valid, How can I get unique (and if possible, shortest ) query string for each given unique text.
any hint will be appreciated, and thx for your help guys!
I create a little function that may help you:
function findQuery(str) {
$("body").children().each(function() {
if ( $.trim($(this).text()) == $.trim(str) ) {
alert("." + $(this).attr("class"))
}
});
}
See working demo
I am not sure what you're actually trying to achieve, but, based on your specific question, you could do the following.
var queryStr = findQuery($('<li class="info"> hello </li>'), "hello"); // queryStr = '.info'
// OR
var queryStr = findQuery('<li class="info"> hello </li>', "hello"); // queryStr = '.info'
alert (queryStr); // returns a string of class names without the DOT. You may add DOT(s) if need be.
function findQuery(html, str) {
var $html = html instanceof jQuery && html || $(html);
var content = $html.text();
if ( content.match( new RegExp(str, "gi") ) ) {
return $html.attr("class");
}
return "no matching string found!";
}
Hope this demo helps you!!
$(document).ready(function() {
var test = $("li:contains('hello')").attr('class');
alert(test);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="info">hello</li>
</ul>
Have used the jQuery attribute ":contains".

Finding and replacing string if present in a JSONObj Javascript

I have a JSONObj which contains various elements. I want to perform a Regex (or some type of search) on the text data of this object and find various strings, and replace them with some other text, for example, I want to replace the string "content" with the string "http://www.example.com/content" :
description = jsonObj.channel.item[jsonCounter].description.replace(/\/content/g, "http://www.example.com/content");
This works perfectly, but I want to first check if a string is present, and then replace it, I tried :
if (holder.indexOf("about-us") !== -1) {
description = jsonObj.channel.item[jsonCounter].description.replace(/\/about-us/g, "http://www.example.com/about-us");
} else {
description = jsonObj.channel.item[jsonCounter].description.replace(/\/content/g, "http://www.example.com/content");
}
But this doesn't seem to work. Can anyone help me solve this issue?
As you said :
holder is my JSONObj converted to a string :
var holder = jsonObj.toString();
var holderJSON = {url:"http://www.example.com/about-us"}
alert(holderJSON.toString()); **// this returns [Object Object]**
if (holder.indexOf("about-us") !== -1) **// is never true.**
Hope this helps!!

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");
}

Categories

Resources