correct a bad generated link using Javascript - javascript

I have a system that dynamically generates links. but the html links are displayed like this :
Page Example
there's a way to remove the repetition of <a> tags using JS ? so, the link becomes :
Page Example

Let's take a look at your url:
var url='Page Example';
First let's get rid of both occurences of "
url=url.replace(/"/g,'');
Now remove the first occurence of </a> by feeding the exact string instead of a regular expression to the .replace method.
url=url.replace('</a>','');
At this point your url looks like this:
Page Example
We're getting closer. Let's remove anything in between the > and the " by
url=url.replace(/\>(.*)\"/,'"');
which gives us
Page Example
Almost done - finally let's get rid of "<a href=
url=url.replace('"<a href=','"');
To make the whole thing a bit more beautiful we can chain all four operations:
var url = 'Page Example';
url = url.replace(/"/g, '').replace('</a>', '').replace(/\>(.*)\"/, '"').replace('"<a href=', '"');
console.log(url);

Within your process you can use regex to extract the url from the href string:
const string = "<a href="/page-example">Page Example</a>";
const url = string.match(/(\/)[\w-]*(?=&)/)[0];
console.log(url);

Yes, using the string split() function like this...
S='<a href="/page-example">Page Example</a>';
var A=split('"');
document.write(A[1]);
This should display "/page-example", and you can then add it as the href to an anchor.

You can retrieve the hrefvalue that seems to be the correct A element and replace the incorrect one with the correct one:
const a = document.querySelector('a[href]'); //if you have more <a> elements replace it to your need
const attr = a.getAttribute('href'); //get the value of 'href' attribute
const temp = document.createElement('template');
temp.innerHTML = attr; //create the new A element from the 'href' attribute's value
const newA = temp.content.children[0]; //retrieve the new <a> element from the template
a.parentElement.replaceChild(newA, a); //replace the incorrect <a> element with the new one
Page Example

Related

javascript regex replace function removes other content

I have a content (string) that in some part contains full urls to youtube and in others just the video ID.
I need to replace the full length youtube urls with the video id only.
var "content" is for example.
var content = '{GENERICO:type="youtube",id="DluFA_AUjV8"}{GENERICO:type="youtube",id="https://youtu.be/DluFA_AUjV8"}';
var myRegex = /{GENERICO:type="youtube",id=".*?(?:youtube\.com|youtu\.be)\/(?:embed\/|watch\?v\=)?([^\&\?\/\"]+).*?["&\?]}/gi;
content = content.replace(myRegex, '{GENERICO:type="youtube",id="$1"}' );
console.log(content);
the result I want to achieve (in the example) is:
{GENERICO:type="youtube",id="DluFA_AUjV8"}{GENERICO:type="youtube",id="DluFA_AUjV8"}
what I actually get is this following:
the result I want to achieve (in the example) is:
{GENERICO:type="youtube",id="DluFA_AUjV8"}
for some reason, it removes one of the strings in the content.
I can't figure out if it's a javascript issue or a regex issue or what i'm doing wrong.
here is the jsfiddle
Use content.replace(new RegExp('https://youtu.be/','g'), '') for a global replace.
var content = '{GENERICO:type="youtube",id="DluFA_AUjV8"}{GENERICO:type="youtube",id="https://youtu.be/DluFA_AUjV8"}';
console.log(content.replace(new RegExp('https://youtu.be/','g'), ''))

How to get 'html string attributes'

I have the following string:
"Site is <a href='javascript:;' xid='01' gid='02' rid='03' >TEST</a> is here "
This is a string with what seems like an 'a' tag inside. I need to get the 'xid', 'gid', and 'rid' values.
If I understand you, you want to get a atributes xid, gid, rid.
You need get link and get atributes. For example:
let link = document.querySelector('a');
if(link!==null){
let xid = a.getAttribute('xid');
let gid = a.getAttribute('gid');
let rid = a.getAttribute('rid');
}
It is faster than using regex;
If you has only string, you can add this string to dom and get current attributes.
Use regex in not true way , because your code will not be flex , and sometimes you can has bugs.

Creating a link tag with parameters

Hi i have a link tag that i am creating from javascript. now i want to append a parameters to that link just like below example.so that when the user clicks that button it should go to that url along with the paramenters
var id="123456789";
var data = ' click' ;
this data tag i am appending to some other element.
now i can able to call /order/product. but when i give id also it is giving error "missing arguments"!!
can anyone please help me?
You'll have to unquote the string where the variable goes
var id = "123456789";
var data = ' click' ;
Or on really up-to-date JavaScript engines that support ES2015+ template literals:
var id = "123456789";
var data = ` click`;
But that won't work on any version of IE (does on Edge).
For easy create link you can use method link(str) of String:
var id="123456789";
var linkText = " click";
var href = "/order/product/" + id;
var data = linkText.link(href);
alert(data);
To make it easier both to write and read (and debug too), I'd recommend the following variant of how to organize the code:
var id = "1234566",
// It is more understandable now that hrefLink contains id concatenated with some other string
hrefLink = "/order/product/" + id,
link = document.createElemen('a');
link.href = hrefLink;
In this way you
See what variable means what
Control what your hrefLink consists of
Follow best practises when instead of multiple lines with var statement you explicitly "show" where the declaration section is:
var a = smth1,
b = smth2;
So just by looking at this code you easier understand that that is a code chunk of variables declaration
You just need to remove the quotes from id
just like below
var id="123456789";
var data = ' click' ;
If You have id within quotes means it will take as string not a variable name and so just remove the quotes. It will work

Get href value from a variable

I have been trying to take out the href value from a variable which contains a link.
This is my variable which contains a link.
var mylink = "<a href='#!takethisout'><img src='http://google.com/'></a>"
I tried to get the value #!takethisout , and I also googled it but there are bunch of pages with how to get the href value from a real link.
Is this possible? Thanks.
I could be wrong, but I think you're asking for a documentFragment so you can extract the href from the string:
var mylink = "<a href='#!takethisout'><img src='http://google.com/'></a>";
var div = document.createElement('div');
div.innerHTML = mylink;
var href = div.firstChild.getAttribute('href');
http://jsfiddle.net/userdude/js8r2/
If you can use jQuery you could do it like this:
var mylink = "<a href='#!takethisout'><img src='http://google.com/'></a>";
var href = $(mylink).attr('href');
alert(href);
Example: http://jsfiddle.net/pn8M4/
What about string split?
var hrefAttr = mylink.split(/href='(.*?)'/)[1]
http://jsfiddle.net/SzHLu/
You need regular expression to parse part string.
mylink.match(/href=["']([^"']+)["']/i)[1];
mylink.split(/href=["']([^"']+)["']/i)[1];
Beware - it doesn't actually parses html and looking for href attribute - it will only find string matching regular expression. so in this case
<a href=#!foobar>
it will NOT work
upd: using split will not break the code in case of non-existent match - thanks #freshbm

Use JS or jQuery to replace part of a URL

Ok, I am not sure what is wrong with me, but I am trying to find and replace a portion of multiple URLs.
Basically, I have some URLs that are being dynamically added to my site. All have a class of 'newsLink' some of the links are pulling up google.docs viewer and I need to remove that.
Here is my code thus far:
$('a.newsLink').each(function(){
var lnk = $('a.newsLink').attr();
var re = new RegExp("http://docs.google.com/viewer?url=","g");
lnk.replace(re, "");
});
the links look like:
<a href='http://docs.google.com/viewer?url=myHomePage.pdf' class='newsLink' target='_blank'>
I would like to remove the first part so that the link looks like:
<a href='http://myHomePage.pdf' class='newsLink' target='_blank'>
Anyway, no luck this far...can anyone please help.
First, you are getting all links again inside of the loop. Then, you try to get an attribute, but didn't say which one. Finally, you try to use replace without assigning the return value to anything.
This is what your code should be:
$('a.newsLink').each(function(){
var lnk = this.href;
this.href = lnk.replace("http://docs.google.com/viewer?url=", "");
});
Note: I'm assuming you want the links to become e.g. myHomePage.pdf, without the protocol.
The regular expression you want is.
http:\/\/docs\.google\.com\/viewer\?url=(.+)
First off, this escapes all regular expression characters. In this case \, ., and ?. We are capturing the document using a group that matches every character ((.+)).
So our code looks like this so far.
$('a.newsLink').each(function(){
var lnk = this.href;
var re = /http:\/\/docs\.google\.com\/viewer\?url=(.+)/g
this.href = lnk.replace(re, "");
});
Now we get the groups like so.
var match = re.exec(lnk);
This returns an array of the matches. Our document is now stored in match[1]. So our final code comes out to.
$('a.newsLink').each(function(){
var lnk = this.href;
var re = /http:\/\/docs\.google\.com\/viewer\?url=(.+)/g
this.href = (re.exec(lnk))[1];
});

Categories

Resources