Find all the links and replace them with their href value - javascript

I think I have a string like:
href text, text, test
And I need to output
site/project/109# text, text, test
I can find all links
var txt = msg.match(/\<a\shref=\"(.*)\"\s(.*)[\<\/a\>]/gmi);
And in loop make replace. But I would like to shorten the code, do everything through single replace, like this :
var txt = msg.replace(/\<a\shref=\"(.*)\"\s(.*)[\<\/a\>]/gmi, $1);
But in this case I get: [object HTMLHeadElement]

Never use regex to parse HTML, it's better to generate an element with the content and do the rest on the element.
var str = 'href text, text, test';
// create an element
var temp = document.createElement('div');
// set the content with the string
temp.innerHTML = str;
// get all `a` tags and convert into array
// for older browser use `[].slice.call()
// for converting into array
Array.from(temp.querySelectorAll('a')).forEach(function(ele) {
// create a text node with the attribute value
var text = document.createTextNode(ele.getAttribute('href'));
// replace a tag wit the text node
ele.replaceWith(text);
});
// get the updated html content
console.log(temp.innerHTML)
Why not regex ? : RegEx match open tags except XHTML self-contained tags
UPDATE : The msg variable is an element object, a not string that's why it's getting converted to [object HTMLHeadElement](HTMLHeadElement refers to the HEAD tag, I think something wrong with your core check that also). So do the same as above where replace temp with the msg. In case you want to keep the original element content then generate temp element as above and set content as temp.innerHTML = msg.innerHTML .

If you're using jQuery (which is great and does all things) then you can get the href quite easily:
var string = 'href text, text, test';
var href = $(string).attr('href');
which means that setting the text of the anchor tag is trivial:
$(string).text($(string).href));

Related

correct a bad generated link using 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

How to get text between two custom html tags in JavaScript?

I am wondering how I can get text between two custom html tags. Example:
const a = "Hello, <num>22</num>";
//And here i want to get only 22 (between these two tags <num></num>
//I've tried something like this:
const nr = a.match(/<num>(.*?)<\/num>/g);
console.log(nr);
//But as you can see, it will only output <num>22</num>
While you could just access the contents using something like innerHTML, to answer your question from an input string via regular expression, you could use the exec() function. This will return an array where the first element is the entire matched string <num>22</num>, and subsequent elements will correspond to the captured groups. So nr[1] will yield 22.
const a = "Hello, <num>22</num>";
const nr = /<num>(.*?)<\/num>/g.exec(a);
console.log(nr[1]);
Note that exec() is a function of RegExp, not String like match() is.
In addition to the provided answers you could also add the string to a new element and search for it normally, for example
const a = "Hello, <num>22</num>";
var wrapper = document.createElement("div");
wrapper.innerHTML = a;
var element = wrapper.getElementsByTagName("num")[0];
console.log(element.innerHTML);
This allows you to match without actually inserting the text into the DOM and allows you to avoid regex which is not safe when parsing html.
It's generally not recommended to parse (x)html using regex.
Just a quick snippet here that works in Chrome, it looks like you can run queries against custom tags and also use the textContent property to get to the inner text:
const customContent = document.querySelector('custom').textContent
console.log(`custom tag's content: ${ customContent }`)
const numContent = document.querySelector('num').textContent
console.log(`num tag's content: ${ numContent }`)
<custom>inner text</custom>
<num>some more inner text</num>

How to parse select second HTML anchor element within a JSON response

I have a JSON response which is returning correctly and have successfully inputted data from it on my HTML page. However, this one JSON value returns some HTML code in which I do not need all of it, just the second anchor element. How would you guys do this?
The code below, the top two work fine. The P element does not. Any ideas? I just get undefined in the console.
// get photo url from description JSON value.
var imageURL = $(description).find('a')[ 1 ];
var parseImageURL = $(imageURL).attr('href');
// get author URL from description JSON value
var authorURL = $(description).find('a')[ 0 ];
var parseAuthorURL = $(authorURL).attr('href');
// get photo description from descriptions JSON value
var descriptionText = $(description).find('P')[5];
console.log(descriptionText);
Parse HTML
You need to "parse" the HTML. There's (at least) two ways to do it:
DOMParser or create an element and stuff the HTML string in there.
The following example shows the second method.
In my example, I assign some string to HTML but you are getting it in some object that you have parsed from JSON.
Create an element. Could be any old element, but I chose div
assign the HTML string to the innerHTML of the element created in step 2
use querySelectorAll to select the node you want. In this example, I selected all of the p elements.
I simply logged out the second p, but in your case, you add it to the page, I assume
let HTML = "<p>something</p><p>else</p>";
let el = document.createElement('div');
el.innerHTML = HTML;
let ps = el.querySelectorAll('p');
console.log(ps[1]);

How to insert HTML entities with createTextNode?

If I want to add an ascii symbol form js to a node somewhere?
Tried as a TextNode, but it didn't parse it as a code:
var dropdownTriggerText = document.createTextNode('blabla ∧');
You can't create nodes with HTML entities. Your alternatives would be to use unicode values
var dropdownTriggerText = document.createTextNode('blabla \u0026');
or set innerHTML of the element. You can of course directly input &...
createTextNode is supposed to take any text input and insert it into the DOM exactly like it is. This makes it impossible to insert for example HTML elements, and HTML entities. It’s actually a feature, so you don’t need to escape these first. Instead you just operate on the DOM to insert text nodes.
So, you can actually just use the & symbol directly:
var dropdownTriggerText = document.createTextNode('blabla &');
I couldn't find an automated way to do this. So I made a function.
// render HTML as text for inserting into text nodes
function renderHTML(txt) {
var tmpDiv = document.createElement("div"); tmpDiv.innerHTML = txt;
return tmpDiv.innerText || tmpDiv.textContent || txt;
}

jquery autocomplete: how to handle special characters (& and ')?

While using jQuery's autocomplete, I've noticed that characters & and ' are
escaped as & and '
Example, autocomplete displays Barbara’s Straight Son but when I
choose this the field shows Barbara's Straight Son.
Any ideas how I can avoid this?
Thank you for your time!
you need to unescape the html entities. the easiest way i found to do that is to use this function:
var unescapeHtml = function (html) {
var temp = document.createElement("div");
temp.innerHTML = html;
var result = temp.childNodes[0].nodeValue;
temp.removeChild(temp.firstChild)
return result;
}
so pass your string through this function before it gets put into your input box. You might have to modify the autocomplete plugin in order to do this.
For example you can set label value in autocomplete using this code
var temp = document.createElement("pre"); // create new DOM element
temp.innerHTML = "Barbara's Straight Son" ; // set string which content HTML entities
return {
label: temp.firstChild.nodeValue, // get string from that DOM element which replace HTML entities to special character
value: "" // set your value here
}

Categories

Resources