Fnd links containing particular string in href and remove href between slashes with javascript only - javascript

I have a use case, where i have to select all <a>, containing string in url like "/web/local" and remove "/web/local" from all href of all these links.
Note: i can't use jQuery. I can use either pure js or YUI.
Thanks in advance.

See comments inline:
let phrase = "/web/local";
// Get all the links that contain the desired phrase into an Array
let links = Array.prototype.slice.call(document.querySelectorAll("a[href*='" + phrase +"']"));
// Loop over results
links.forEach(function(link){
// Remove the phrase from the href
link.href = link.href.replace(phrase, "");
});
// Just for testing:
console.log(document.querySelectorAll("a"));
Some Link
Some Link
Some Link
Some Link
Some Link

In order to get /set correctly the href attribute you need to use getAttribute/setAttribute:
document.querySelectorAll('a[href*="/web/local"').forEach(function(ele) {
ele.setAttribute('href',
ele.getAttribute('href').replace('/web/local', ''));
console.log(ele.outerHTML);
});

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
Link 1
Link 2
<script>
var string = '/web/locale/';
var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
var link = links[i].getAttribute('href');
link = link.replace(string, '');
links[i].setAttribute('href', link);
}
</script>
</body>
</html>

Related

My Extensions Google Chrome Does not Work?

I create a simple code to extract URL from a website
but it's not working when I click on icon extensions
My js code
var el = document.getElementById('myPopup');
el && el.addEventListener('click', yourFunction, false);
function yourFunction() {
let x = document.querySelectorAll("a");
let myarray = [];
for (let i = 0; i < x.length; i++) {
let nametext = x[i].textContent;
let cleantext = nametext.replace(/\s+/g, " ").trim();
let cleanlink = x[i].href;
myarray.push([cleantext, cleanlink]);
}
function make_table() {
let links_table = "<table><thead><th>Name</th><th>Links</th></thead><tbody>";
for (let i = 0; i < myarray.length; i++) {
links_table += "<tr><td>" + myarray[i][0] + "</td><td>" + myarray[i][1] + "</td></tr>";
}
let w = window.open("");
w.document.write(links_table);
console.log(w);
console.log(links_table);
}
make_table();
}
yourFunction();
My HTML code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<dev>
<button id="myPopup">Clickme</button>
</dev>
<script src="popup.js"></script>
</body>
</html>
when i click on Clickme the url not show me just empty table
can you tell me where is the Error?
video
imgur.com/a/0OS60qG
The error happens since the popup script does not have access to the list of "a" tags. When you ran it on the browser console it works cause you are manipulating the page content, meanwhile, on the popup, it only interacts with the popup.html page.
Content scripts should be the only scripts able to manipulate the page content, so to fix that you probably should send a message to a content script when clicking on the button, so the content script can scrap the links and send them as a response to the popup or output as you want.
This other question may help you to see how to send messages between files:
How to send the message from popup.html to content script?

React not getting different images for same URL

I am making a users page with arbitrary data and noticed that since the image URL is the same (https://source.unsplash.com/random) the image is the same. How can I prevent this?
That is because, your browser caches your url and assumes you are hitting the same url so it populates previous result. Add a random query to the url like source.unsplash.com/random?v={random_number_here} will solve your problem
This has nothing to do with react.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="images-wrapper"></div>
<script>
const wrapper = document.getElementById('images-wrapper');
var html = '';
// for(var i =0; i< 10; i++){ // same images
// html += '<img src="https://source.unsplash.com/random">';
// }
for(var i =0; i< 10; i++){ // different images
html += '<img src="https://source.unsplash.com/random?v='+(i+1)+'">';
}
wrapper.innerHTML = html;
</script>
</body>
</html>

document.creatElement can't show utf8 chars

I create label elem with document.crteateElement and I set text value to elem with .innerHTML but on page browser don't show utf-8 characters correct I see only '?' in black rectangle.
This my hrml charset:
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-9">
<META HTTP-EQUIV="Content-language" CONTENT="tr">
I use this function for convert :
GetChar(char) {
return unescape(decodeURIComponent(char))
}
and this is my value
const target= '${this.GetChar('İ')}stikamet'
then here is I set value to label elem
var elem = document.createElement('label)
elem.innerHTML = target
What is the corrent way show this characters on browser ?
Try this instead of your current meta-tags
<meta charset="UTF-8">
EDIT:
The following HTML displays your example-char fine for me:
<html>
<meta charset="UTF-8">
<body>
<label>İ</label>
</body>
</html>

How to replace text in a html document using Javascript

I have written this code which I thought was correct, but although it runs without error, nothing is replaced.
Also I am not sure what event I should use to execute the code.
The test a simple template for a landing page. The tokens passed in on the url will be used to replace tags or tokens in the template.
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
// gets passed variables frm the url
function getQueryVar(str) {
return 'Newtext'; // JUST SCAFFOLD FOR TESTING
}
function searchReplace() {
/**/
var t = 0;
var tags = Array('keyword', 'locale', 'advert_ID');
if (document.readyState === 'complete') {
var str = document.body.innerText;
for (t = 0; t < tags.length; t++) {
//replace in str every instance of the tag with the correct value
if (tags[t].length > 0) {
var sToken = '{ltoken=' + tags[t] + '}';
var sReplace = getQueryVar(tags[t]);
str.replace(sToken, sReplace);
} else {
var sToken = '{ltoken=' + tags[t] + '}'
var sReplace = '';
str.replace(sToken, sReplace);
//str.replace(/sToken/g,sReplace); //all instances
}
}
document.body.innerText = str;
}
}
</script>
</head>
<body>
<H1> THE HEADING ONE {ltoken=keyword}</H1>
<H2> THE HEADING TWO</H2>
<H3> THE HEADING THREE</H3>
<P>I AM A PARAGRAPH {ltoken=keyword}</P>
<div>TODO write content</div>
<input type="button" onclick="searchReplace('keyword')">
</body>
</html>
So when the documment has finished loading I want to execute this code and it will replace {ltoken=keyword} withe value for keyword returned by getQueryVar.
Currently it replaces nothing, but raises no errors
Your problem is the fact you don't reassign the replacement of the string back to it's parent.
str.replace(sToken,sReplace);
should be
str = str.replace(sToken,sReplace);
The .replace method returns the modified string, it does not perform action on the variable itself.
Use innerHTML instead innerText and instead your for-loop try
tags.forEach(t=> str=str.replace(new RegExp('{ltoken='+ t+'}','g'), getQueryVar(t)))
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
// gets passed variables frm the url
function getQueryVar(str)
{
return'Newtext';// JUST SCAFFOLD FOR TESTING
}
function searchReplace() {
/**/
var t=0;
var tags =Array('keyword','locale','advert_ID');
if (document.readyState==='complete'){
var str = document.body.innerHTML;
tags.forEach(t=> str=str.replace(new RegExp('{ltoken='+ t+'}','g'), getQueryVar(t)));
//tags.forEach(t=> str=str.replace(new RegExp('{ltoken='+ tags[t]+'}', 'g'), getQueryVar(tags[t])));
document.body.innerHTML=str;
}
}
</script>
</head>
<body >
<H1> THE HEADING ONE {ltoken=keyword}</H1>
<H2> THE HEADING TWO</H2>
<H3> THE HEADING THREE</H3>
<P>I AM A PARAGRAPH {ltoken=keyword}</P>
<div>TODO write content</div>
<input type ="button" onclick="searchReplace('keyword')" value="Clicke ME">
</body>
</html>

How to store the value of an attribute inside a variable using html, javascript?

I have a line <meta property="product:price:amount" content="3.05"/>
in a large html file.
I need to store the value of content inside a variable, so that I may access it globally.
How can I do that?
Just catch it with querySelector to get it's content attribute.
const content = document.querySelector('meta').content;
console.log(content);
<meta property="product:price:amount" content="3.05"/>
In case of multiple meta tags:
const elems = document.querySelectorAll('meta');
let content = Array.from(elems).find(v => v.content).content;
console.log(content);
<meta property="product:price:amount"/>
<meta property="product:price:amount"/>
<meta property="product:price:amount" content="3.05"/>
To very specifically get the meta tag you are after (event if there are multiple meta tags):
var variable = document.querySelectorAll('meta[property="product:price:amount"]')[0].content;
If there is only one item then simply
document.getElementsByTagName("meta")[0].content
For a single meta tag:
var myGlobal = document.querySelector('meta[content]').getAttribute('content');
document.body.textContent = myGlobal;
<meta property="product:price:amount" content="3.05"/>
If you have a lot of tags:
var contentArray = [];
document.querySelectorAll('meta[content]').forEach(function(meta){
contentArray.push(meta.getAttribute('content'));
});
document.body.textContent = contentArray.join(' - ');
<meta property="product:price:amount" content="3.05"/>
<meta property="product:quality:amount" content="9.25"/>
<meta property="product:id:amount" content="1.0"/>
If you want to be more specific about the tag you can change the selector:
...querySelector('meta[property="product:price:amount"][content]')...
Read more about selectors https://developer.mozilla.org/en-US/docs/Learn/CSS/Introduction_to_CSS/Selectors

Categories