How do I replace all URLs of a target domain in html code? [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed last year.
Improve this question
I'm trying to replace all HREF with domain1.com with the URL described in his title (if it has a title).
var els = document.getElementsByTagName('a'),
for (els in url) {
if (url.includes(domain1)); {
var titulo = url.attr('title');
var enlace = url.attr('href');
url.replace(enlace, titulo);
}
}
<p style="margin:40px;" line-height:2px;=""><img src="https://www.domain1.com/738956_1.jpg" data-width="1070" data-height="1387" data-image="738956-sanKH" alt="738956-sanKH.jpg">XS texto<br>
<img src="https://www.domain1.com/738956_1.jpg" data-width="1077" data-height="1693" data-image="738956-iMkWh" alt="738956-iMkWh.jpg">S texto</p>
I'm a beginner in javascript. Sure have a lot of format mistakes. Thanks in advance

Here is a tested JavaScript code, replace the for..of with for..in if you want to support Internet Explorer browser.
var domain1 = 'domain1.com';
var els = document.getElementsByTagName('a');
for (var url of els) {
var title = url.getAttribute('title');
if (title && url.getAttribute('href').search(domain1) !== -1) {
url.setAttribute('href', title);
}
}

If your DOM is having all the links after document load, then you can do this:
window.onload = bindEvents;
function bindEvents() {
// replace href with title
bindAnchorTitleAsHref();
}
function bindAnchorTitleAsHref() {
const els = document.getElementsByTagName('a');
for (let i = 0; i < els.length; i += 1) {
const title = els[i].getAttribute('title');
const href = els[i].getAttribute('href')
els[i].setAttribute('href', title);
console.log('New Href set :', els[i].getAttribute('href'), 'instead of', href);
}
}
<a
href="https://www.domian1.com/plants"
title="https://www.newdomain.com/test1"
target="_blank"
rel="nofollow noopener"
>
texto
</a>

If you just want to update the domain of the link, then you can use the URL class:
document.addEventListener('DOMContentLoaded', () => {
document.querySelectorAll('a[title]').forEach(el => {
const href = new URL(el.href);
if ((/[\^\.]domain1.com$/i).test(href.host)) {
const title = new URL(el.title);
href.host = title.host;
el.href = href.toString();
}
});
});
<p style="margin:40px;" line-height:2px;=""><img src="https://www.domain1.com/738956_1.jpg" data-width="1070" data-height="1387" data-image="738956-sanKH" alt="738956-sanKH.jpg">XS texto<br>
<img src="https://www.domain1.com/738956_1.jpg" data-width="1077" data-height="1693" data-image="738956-iMkWh" alt="738956-iMkWh.jpg">S texto</p>

Related

How hide javascript on specific page [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 days ago.
Improve this question
I have a javascript code for our online chat that we use in our application. But I need this code to not appear on a specific page, eg domain/X1XY.
Can you advise me how I can write this in the main code that is called on each of our pages?
<!-- Smartsupp Live Chat script -->
<script type="text/javascript">
var _smartsupp = _smartsupp || {};
_smartsupp.key = '123456789';
window.smartsupp||(function(d) {
var s,c,o=smartsupp=function(){ o._.push(arguments)};o._=[];
s=d.getElementsByTagName('script')[0];c=d.createElement('script');
c.type='text/javascript';c.charset='utf-8';c.async=true;
c.src='https://www.smartsuppchat.com/loader.js?';s.parentNode.insertBefore(c,s);
})(document);
</script>
If the URL of the page is unique, then you can use it to conditionally run the JavaScript using the document object's URL property:
<script type="text/javascript">
if (document.URL !== 'https://<your URL here>') {
var _smartsupp = _smartsupp || {};
_smartsupp.key = '123456789';
window.smartsupp ||
(function (d) {
var s,
c,
o = (smartsupp = function () {
o._.push(arguments);
});
o._ = [];
s = d.getElementsByTagName('script')[0];
c = d.createElement('script');
c.type = 'text/javascript';
c.charset = 'utf-8';
c.async = true;
c.src = 'https://www.smartsuppchat.com/loader.js?';
s.parentNode.insertBefore(c, s);
})(document);
}
</script>
Hope this helps.
if (window.location.pathname !== '/X1XY') { // your code here }

How to dynamically change a text from URL input?

I want something like that..
https://pl.sports-streams-online.best/?st=nbastream.tv&plcm=db&q=Raptors+vs+Lakers
See that URL part q=Raptors+vs+Lakers, If i input any text on this section it will automatically change on website body. I want to know how i can do this. I will input a text in URL and it will display on website body.
Thanks for advance.
You can parse window.location and put that into a div on your page. I can't show you in a code snippet because the snippets use an iframe but if your html has <div id='uText'></div> then you can use javascript (after the page has loaded) to set the value of that div with results of the query param. lets say your url ends in ?st=nbastream.tv&plcm=db&q=Raptors+vs+Lakers, then you want the value for parameter 'q':
function getQueryStringParam(param) {
var url = window.location.toString();
url.match(/\?(.+)$/);
var params = RegExp.$1;
params = params.split("&");
var queryStringList = {};
for(var i = 0; i < params.length; i++) {
var tmp = params[i].split("=");
queryStringList[tmp[0]] = unescape(tmp[1]);
}
return decodeURIComponent(queryStringList[param]);
}
let qParam = getQueryStringParam('q').split('+').join(' ');
const div = document.getElementById('uText');
div.innerHTML = qParam;
Check out the codepen here.

How to store a variable in an Array using AngularJS? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Is there any function that i can use?
Or i need to create one? Or can i use push? It is modified script from this page:
http://code-maven.com/automatic-counter-using-angularjs
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
<script>
angular.module('CounterApp', [])
.controller('CounterController', function($scope, $timeout) {
var timer;
$scope.stored = [];
$scope.counter= 0;
$scope.stopCounter = function() {
$timeout.cancel(timer);
timer = null;
};
$scope.startCounter = function() {
if (timer === null) {
updateCounter();
}
$scope.stored.push(counter);
};
$scope.pushedVariable = function() {
$scope.stored.push(counter);
};
var updateCounter = function() {
$scope.counter++;
timer = $timeout(updateCounter, 1000);
};
$timeout.cancel(timer);
timer = null;
});
</script>
<div ng-app="CounterApp">
<div ng-controller="CounterController">
<button ng-click="stopCounter()">Stop</button>
<button ng-click="startCounter()">Start</button>
<button ng-click="pushedVariable()">Push</button>
{{counter}}
<p>Stored Variable 1: {{stored[0]}}</p>
<p>Stored Variable 2: {{stored[1]}}</p>
</div>
</div>
You just need to use $scope.stored.push($scope.counter); in your function instead of your current $scope.stored.push(counter); which is an undefined variable.
function(obj) {
var str = [];
for(var val in obj)
str.push(encodeURIComponent(val) + "=" + encodeURIComponent(obj[val]));
}
Where "obj" is your object.

How to add target = "_blank" in case

I am using Vanilla 2 as forum with buttonbar plugin to create pre tags in the message area.
When clicking on the url button, he generates in the message box, but I would prefer <a href="" target="_blank></a> to generate.
Here is is the .js with the case for the url attribute:
case 'url':
var urlOpts = {};
var thisOpts = $.extend(htmlOpts, {
center: 'href'
});
var hasSelection = $(TextArea).hasSelection();
var NewURL = '';
if (hasSelection !== false) {
NewURL = hasSelection;
delete thisOpts.center;
} else
NewURL = prompt("Enter your URL:",'http://');
urlOpts.href = NewURL;
$(TextArea).insertRoundTag('a',thisOpts,urlOpts);
break;
Can someone tell me how to add the target="_blank" in it?
It seems to be solved so maybe here could be useful for anyone:
I don't know exactly the technologies u are using but have u tried with
urlOpts.target = '_blank';
before
$(TextArea).insertRoundTag('a',thisOpts,urlOpts);

remove first half of string but keep second half in javascript or jquery

I recently created my own personal portal page to replace iGoogle since it's going to be shuttered later this year. Everything is working fine except that one of the RSS feeds that I'm pulling in outputs urls that look like this: http://news.google.com/news/url?sa=t&fd=R&usg=AFQjCNFEguC5pqagsWkkW_y_EjYj9n1bMg&url=http://www.haaretz.com/news/diplomacy-defense/israel-to-un-replace-austrian-peacekeepers-withdrawn-from-golan-1.528305
Which when clicked go to a bad url page. How would I remove the first half of that url so that it only has the part starting from the second http://
Strange, but here the link works fine...
Just realized the issue is that somehow the ampersands are being turned into entities which is breaking the links...
Try this. A generic approach.
function queryString(parameter, url) {
var a = document.createElement("a");
a.href = url;
var loc = decodeURIComponent(a.search.substring(1, a.search.length));
var param_value = false;
var params = loc.split("&");
for (var i = 0; i < params.length; i++) {
param_name = params[i].substring(0, params[i].indexOf('='));
if (param_name == parameter) {
param_value = params[i].substring(params[i].indexOf('=') + 1)
}
}
if (param_value) {
return encodeURIComponent(param_value);
}
else {
return "";
//param not found
}
}
var secondHTTP = queryString("url", 'http://news.google.com/news/url?sa=t&fd=R&usg=AFQjCNFEguC5pqagsWkkW_y_EjYj9n1bMg&url=http://www.haaretz.com/news/diplomacy-defense/israel-to-un-replace-austrian-peacekeepers-withdrawn-from-golan-1.528305');
var str = "http://news.google.com/news/url?sa=t&fd=R&usg=AFQjCNFEguC5pqagsWkkW_y_EjYj9n1bMg&url=http://www.haaretz.com/news/diplomacy-defense/israel-to-un-replace-austrian-peacekeepers-withdrawn-from-golan-1.528305";
var url = decodeURIComponent(str.split(/https?:/ig).pop());
will result in
"//www.haaretz.com/news/diplomacy-defense/israel-to-un-replace-austrian-peacekeepers-withdrawn-from-golan-1.528305"
or
var url = decodeURIComponent(str.match(/^http.+(http.+)/i)[1]);
will result in
"http://www.haaretz.com/news/diplomacy-defense/israel-to-un-replace-austrian-peacekeepers-withdrawn-from-golan-1.528305"
Edit: Code updated, jsFiddle added
HTML:
<input id="schnitzel" type="text" value="http://www.google.com/http://www.real-foo.bar/" />
<input type="button" onclick="$('#schnitzel').val(window.firstHTTP($('#schnitzel').val()));" value="ยป" />
JavaScript:
window.firstHTTP = function (furl = "") {
var chunked = furl.split("http://");
return (chunked && chunked[2]) ? ("http://" + chunked[2]) : furl;
};
JS-Fiddle:
http://jsfiddle.net/Rm5bU/

Categories