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.
Related
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
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>
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'), ''))
as i am getting tough time to list out all spans, which having class="ansspans", may be one or more span with "ansspans" classes will be there, i need to get all the spans with its content and iterate through it. can you tell me how to do it, Regex, Jquery, any thing ok,
The content will be in string variable (not in DOM), as IE 9 ignoring quotes from attribute, so i cant use getelementbyclass name,and i followed this answer, to get quotes InnerHTml workAround, now its displaying with quotes. so i need get all the class of ansspans, in an array, so that i'll iterate it n get the text content of each span
<span id="sss_ctl00_ctl06_lblanswertext">
assignment
<span class="ansspans">submission </span>
date : 10:07:51 AM
</span>
in this eg, expected output will be 1 span object, so that i can iterate over it
Update : I cant use DOm, as we are in quirks mode, so ie 9 will ignore attribute quotes, which i cant traverse using getelement by class name, . so , i need to match all spans in a string variable. hope everyone understood my problem ;(
(as been said on this site before, sometimes it's ok to parse a limited, known set of xml with regex)
//assumes no <span id="stupid>" class="ansspans">, and no embedded span.ansspans
var data = ' <span id="sss_ctl00_ctl06_lblanswertext"> assignment \n date : 10:07:51 AM \n <span class="ansspans">ONE has a new \n line in it</span><span class="ansspans">TWO</span><span class="ansspans">3 </span><span class="ansspans">4 </span><span class="ansspans">5 </span>';
var myregexp = /<span[^>]+?class="ansspans".*?>([\s\S]*?)<\/span>/g;
var match = myregexp.exec(data);
var result = "spans found:\n";
while (match != null) {
result += "match:"+RegExp.$1 + ',\n';
match = myregexp.exec(data);
}
alert(result);
(edited to capture inner html instead of whole tag)
The following jQuery selector $('span.ansspans') will get all the <span class="anspans"> for the page.
If you need something for a specific element, add a prefix of the appropriate selector, i.e. $('#sss_ctl00_ctl06_lblanswertext span.ansspans')
If this needs to be done in a more dynamic way - look into functions like find(), filter(), etc.
solution using jquery
var tempArray = $("span.ansspans");//this will select all the span elements having class 'ansspans' and return them in an array
var len = tempArray.length;//calculate the length of the array
for(var index = 0;index<len;index++){
var reqString = $(tempArray[index]).html();
}
These string values can be either put inside an array or can be utilised then and there only.
If you want textContent, use .text() instead of .html()
I am in need of two regular expressions.
First of all I want to check if my URL contains the hashtag #videos. Then if it does, I want to get the value of the second #tag. That value could contain all kinds of characters;
http://local/default.php#videos#12345
http://local/default.php#videos#g5458f
http://local/default.php#videos#0-e4a5d
This is what I've got so far:
if (window.location.hash = 'videos') {
var url = window.location.hash,
id = url.match(regex-goes-here); // output e.g string '12345'
}
(Not sure if my extremely simple check (window.location.hash = 'videos') will work on two hashtags..? There is probably a better way of checking the URL, if so, please do tell :-)
You can get an array of tags like this:
var tags = window.location.hash.replace(/^#/, '').split('#');
In case of http://local/default.php#videos#12345, tags[0] will be videos and tags[1] will be 12345. You can use tags.length to determine how many tags there are.