JavaScript Regx to remove certain string if a pattern is found - regex

Lets say i have
input string as
<div id="infoLangIcon"></div>ARA, DAN, ENGLISHinGERMAN, FRA<div id="infoPipe"></div><div id="infoRating0"></div><div id="infoPipe"></div><div id="infoMonoIcon"></div>
so i want to check if inforating is 0 and then remove the div and previous div also. The output is
<div id="infoLangIcon"></div>ARA, DAN, ENGLISHinGERMAN, FRA</div><div id="infoPipe"></div><div id="infoMonoIcon"></div

Regex is not your best option here. It is not reliable when it comes to HTML.
I suggest you use DOM functions to do this (I gave you a Javascript example, you have not provided a language to be used). If I understood correctly, if there is an element with the ID of infoRating0, you want to remove it and its previous sibling. This little snippet should do that:
if (document.getElementById('infoRating0')) {
var rating0=document.getElementById('infoRating0'),
rParent=rating0.parentNode;
rParent.removeChild(rating0.previousSibling);
rParent.removeChild(rating0);
}
Also, your HTML is invalid. You can only use an ID once in your HTML. You have two divs with the same ID (infoPipe) which you should REALLY fix. Use classes instead.
jsFiddle Demo

Related

Removing entire tags containing a specific term using regex

I am altering a database with approximately 500 html pages using phpmyadmin.
Several pages contain a Facebook Pixel or Google Tag that I would like to remove.
The easiest way I thought would be to search via regex the entire tag that contains some expression or term related to Facebook or Google, and replace it with blank.
An example would be
<script>
window.dataLayer = window.dataLayer || [];
function gtag() {
dataLayer.push(arguments);
}
gtag('js', new Date());
gtag('config', 'G-XXXXXXXX');
</script>
or
<script>
(window, document, 'script', 'https://connect.facebook.net/en_US/fbevents.js');
fbq('init', '9999999999999999');
fbq('track', 'salespage_xxxxxx');
</script>
Although all are unique, some have the same code or another element that makes it possible to identify each one of them.
Before running in myphpadmin, I'm trying to formulate the expression using SublimeText3
It's the first contact I have with the regex and I found it fascinating, but even following some references I can't match the search.
The expression I came up with after some research was
<(.*)>[\s\S]face[\s\S]<\/(.*)>
Where I thought the expression would select the entire tag containing the word "face", but it doesn't find anything.
I would like some help.
If it works, it would be able to make several other necessary changes.
This regex expression will match the <script> tag that contains the face keyword
<(script)>(?:(?!<\/\1>|face)[\s\S])+face(?:(?!<\/\1>)[\s\S])+<\/\1>
See example: https://regex101.com/r/LfRlBV/1

Binding HTML strings in Ember.JS

I am using a third party indexing service (Swiftype) to search through my database. The returned records contains a property called highlight. This simply adds <em> tags around matching strings.
I then bind this highlight property in Ember.JS Handlebars as such:
<p> Title: {{highlight.title}} </p>
Which results in the following output:
Title: Example <em>matching</em> text
The browse actually displays the <em> tags, instead of formatting them. I.e. Handlebars is not identifying the HTML tags, and simply printing them as a string.
Is there a way around this?
Thanks!
Handlebars by default escapes html, to prevent escaping, use triple brackets:
<p> Title: {{{highlight.title}}} </p>
See http://handlebarsjs.com/#html-escaping
Ember escapes html because it could be potentional bad code which can be executed. To avoid that use
Ember.Handlebars.SafeString("<em>MyString</em>");
Here are the docs
http://emberjs.com/guides/templates/writing-helpers/
if you've done that you could use {{hightlight.title}} like wished,...
HTH

How to find attribute values using regular expression with Selenium WebDriver?

The HTML is as follows:
<div class="item link-color-1
automated link-track logout-link"
data-track-category="Logout"
data-track-action="Logout from /myaccount/mymoney/cashier"
data-data-automated-function="clickTracker"> logout </div>
To find the x path of a link, tried something like: //*[contains(#data-track-category='Logout']. But its not working. Please help.
If you are just trying to find the element itself (and not the value of the attribute as your question title implies), you could always use CSS (its my selector of choice over XPath).
You have not indicated which language bindings you use, so this is how I would find it in Ruby by using only the data-track-category attribute to select the element:
#driver.find_element(:css => "[data-track-category='Logout']")
Of course, the same applies across all the bindings. Just use the value "[data-track-category='Logout']" for your CSS method.
You can always store the given element in a WebElement and then using the getAttribute() method. You can find the documentation here
WebElement myDiv = driver.findElement(By.className("logout-link"));
String attributeValue = myDiv.getAttribute("data-track-category");
This should work on Java. Not sure that's the language you are looking for or if you must use regex for it.

Django: How do I prepend

I'm exploring Django and got this particular problem.
How do I prepend <span class="label">Note:</span> inside {{article.content_html|safe}}?
The content of {{article.content_html|safe}} are paragraph blocks, and I just wanna add <span class="label">Note:</span> in the very first paragraph.
Thanks!
Sounds like you want to write a custom tag that uses BeautifulSoup to parse the HTML and inject the fragment.
There's no easy way. You can easily prepend to all articles.
<span class="label">Note:</span>
{{article.content_html|safe}}
If that doesn't help you consider changing the structure of article.content_html so you can manipulate with blocks from django templates, so it should look something like this
{{article.content_header}}
<span class="label">Note:</span>
{{article.content_html}}
If that solution is not feasible to you and you absolutely need to parse and modify the content of article.content_html, write your own custom filter that does that. You can find documentation about writing custom filters here http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-filters.
An alternate approach could be to do this with javascript. In jQuery, it would look something like:
var first_p_text = $("p:first").text()
$("p:first").html("<span class="label">Note:</span>" + first_p_text)
Note though that if there are other elements inside your first p, $("p:first").text() will grab the text from those as well - see http://api.jquery.com/text/
Of course, this relies on decent javascript support in the client.
jQuery is the simplest and easiest to implement. You only need one line with the prepend call (documentation):
$('p:first').prepend('<span class="label">Note:</span>');
Explanation: 'p:first' is a jQuery selector similar to the ':first-child' CSS selector. It will select the first paragraph and the prepend call will then insert the span into that selected paragraph.
Note: If there is a paragraph on the page before your content, you may have to surround it with a div:
<div id='ilovesmybbq'>{{article.content_html|safe}}</div>
Then the jQuery call would be:
$('#ilovesmybbq p:first').prepend('<span class="label">Note:</span>');

Replacing a substring using regular expressions

I want to add a call to a onclick event in any href that includes a mailto: tag.
For instance, I want to take any instance of:
<a href="mailto:user#domain.com">
And change it into:
<a href="mailto:user#domain.com" onclick="return function();">
The problem that I'm having is that the value of the mailto string is not consistent.
I need to say something like replace all instances of the '>' character with 'onclick="return function();">' in strings that match '<a href="mailto:*">' .
I am doing this in ColdFusion using the REreplacenocase() function but general RegEx suggestions are welcome.
The following will add your onclick to all mailto links contained withing a string str:
REReplaceNoCase(
str,
"(<a[^>]*href=""mailto:[^""]*""[^>]*)>",
"\1 onclick=""return function();"">",
"all"
)
What this regular expression will do is find any <a ...> tag that looks like it's an email link (ie. has an href attribute using the mailto protocol), and add the onclick attribute to it. Everything up to the end of the tag will be stored into the first backreferrence (referred to by \1 in the replacement string) so that any other attributes in the <a> will be preserved.
If the only purpose of this is to add a JavaScript event handler, I don't think Regex is the best choice. If you use JavaScript to wire up your JavaScript events, you'll get more graceful degradation if JS is not available (e.g. nothing will happen, instead of having onclick cruft scattered throughout your markup).
Plus, using the DOM eliminates the possibility of missing matches or false positives that can occur from a Regex that doesn't perfectly anticipate every possible markup formation:
function myClickHandler() {
//do stuff
return false;
}
var links = document.getElementsByTagName('a');
for(var link in links) {
if(link.href.indexOf('mailto:') == 0) {
link.onclick = myClickHandler;
}
}
Why wouldn't you do this on the frontend with a library like jQuery?
$(function(){
$("a[href^=mailto]").click(function(){
// place the code you want to execute here
})
});