Add html attribute to string with javascript replace (regexp) - javascript

i need to add a ng-click attribute to a IMG tag present in a string, using String.replace.
Example:
<p>Test1</p>
<p>
<img class="fr-dib fr-draggable" src="http://admin.fsn.dev/uploads/a4cafaf13aabb97b041a50ae55c7bb6d331a7cc4.jpg">
Foto1
</p>
<p>
<img class="fr-dib fr-draggable" src="http://admin.fsn.dev/uploads/c5a7fc84d8f552d208e5ee0e0cbcecc0d547b441.jpg" style="width: 300px;">
</p>
Needs to be converted to:
<p>Test1</p>
<p>
<img class="fr-dib fr-draggable" src="http://admin.fsn.dev/uploads/a4cafaf13aabb97b041a50ae55c7bb6d331a7cc4.jpg" ng-click="openModal('http://admin.fsn.dev/uploads/a4cafaf13aabb97b041a50ae55c7bb6d331a7cc4.jpg')">
Foto1
</p>
<p>
<img class="fr-dib fr-draggable" src="http://admin.fsn.dev/uploads/c5a7fc84d8f552d208e5ee0e0cbcecc0d547b441.jpg" ng-click="openModal('http://admin.fsn.dev/uploads/c5a7fc84d8f552d208e5ee0e0cbcecc0d547b441.jpg')" style="width: 300px;">
</p>
Any suggestion?
I tried with this but no luck :(
data = data.replace(/<img(.*)src="(.*)"(.*)>/ig,'<img $1 src="$2" ng-click="openModal(\'$2\')" $3')

Related

Javascript Regex - add only a character to matched string

I am trying to create a JS regex that matches a a string inside a given piece of code by it's beggining and ending and then only adds one character to that matched string.
Please see below what I mean:
Imagine that I supply the following code:
<div>
<p>This is just some random text</p>
<a href="https://somerandomsrc.com">
<img src="https://somerandomsrc.com" alt="random image">
</a>
<img src="https://someotherrandomsrc.com" alt="another random image">
</div>
What I need to do is to have the script finding all instances of <img> and add a closing slash to the <img> elements so I would have something like this:
<div>
<p>This is just some random text</p>
<a href="https://somerandomsrc.com">
<img src="https://somerandomsrc.com" alt="random image" />
</a>
<img src="https://someotherrandomsrc.com" alt="another random image" />
</div>
Any help will be appreciated.
Regards,
T
Usually regex should be avoided for dealing with html/xml, but since your img tag seems broken and img tags are not nested, you can use following regex,
(<img[^>]*)>
and replace it with
$1 />
and fix your broken img tags.
Demo
const s = `<div>
<p>This is just some random text</p>
<a href="https://somerandomsrc.com">
<img src="https://somerandomsrc.com" alt="random image">
</a>
<img src="https://someotherrandomsrc.com" alt="another random image">
<img src="https://someotherrandomsrc.com" alt="another random image" />
</div>`
console.log('Before: ' + s);
console.log('After: ' + s.replace(/(<img[^>]*[^/])>/g,'$1 />'));
Edit1:
Yes just change the regex to (<img[^>]*[^/])> so that it won't match the one which already has a proper closing tag />.
Updated Demo
Just select the img and its content in a group (<img\s.*?) except the closing tag and use replace with a global flag to replace after it with / slash.
const string = `<div>
<p>This is just some random text</p>
<a href="https://somerandomsrc.com">
<img src="https://somerandomsrc.com" alt="random image">
</a>
<img src="https://someotherrandomsrc.com" alt="another random image">
</div>`
const result = string.replace(/(<img\s.*?)>/g, '$1 />')
console.log(result)

Replace image title attributes on specific classes in jQuery

I'm trying to swap out the title attribute on all images on the page that contain the string slide in the class name. The image class names vary and are followed by a unique numeric string (ex: slide-1234, slider-4321) so it's important it just contains the string slide. I want to replace it with the WordPress post title. Here is my code so far (doesn't work)
<script>
var title = '{{get_the_title()}}';
$('img[class*=slide]').attr('title', title);
</script>
Very simple, but unfortunately doesn't work. I used alert to debug and was able to print the title, but the selector is the issue.
Here's the HTML
<h6 class="text-primary mb-5 mt-5">Session Photos</h6>
<div id="metaslider-id-1572" style="width: 100%;" class="ml-slider-3-15-3 metaslider metaslider-flex metaslider-1572 ml-slider">
<div id="metaslider_container_1572">
<div id="metaslider_1572">
<ul aria-live="polite" class="slides">
<li style="display: block; width: 100%;" class="slide-1573 ms-image"><img src="https://knowledge.page.org/wp-content/uploads/2019/07/DSC04292-850x500.jpg" height="500" width="850" alt="" class="slider-1572 slide-1573" title="DSC04292" /></li>
</ul>
</div>
</div>
</div>
I believe your script is running before the DOM is fully loaded. You can either place the script code at the bottom of the body tag OR try wrapping your code with $(document).ready(function(){...}).
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var title = 'someTitle';
$('img[class*=slide-]').attr('title', title);
});
</script>
<h6 class="text-primary mb-5 mt-5">Session Photos</h6>
<div id="metaslider-id-1572" style="width: 100%;" class="ml-slider-3-15-3 metaslider metaslider-flex metaslider-1572 ml-slider">
<div id="metaslider_container_1572">
<div id="metaslider_1572">
<ul aria-live="polite" class="slides">
<li style="display: block; width: 100%;" class="slide-1573 ms-image"><img src="https://knowledge.page.org/wp-content/uploads/2019/07/DSC04292-850x500.jpg" height="500" width="850" alt="" class="slider-1572 slide-1573" title="DSC04292" /></li>
</ul>
</div>
</div>
</div>

JS / jQuery - How together innerHTML of targeted element of a certain class and append /replace it?

I want to get the text on click with a certain class but nothing works. I have a div with 2 p tags and I want to get both separate. Also, I want to append them. .append() appends but just keeps adding all targeted events. empty().append() gives me random results (on first click it works, on second I get half of the text etc). Ive tried most of what I could find on stack overflow but nothing helped. Any help would be great!
Ive tried:
$(event.target).text(); //that gives me the text, but not both p elements separate
$(this).hasClass('.video-title'); //only returns to me true/false
var title= document.getElementsByClassName("video-title")[0].innerHTML; //doesn't give me the current element.
$('p.video-title').innerHTML; //doesnt help either
HTML
<div class="video-container">
<iframe id="vid_frame" src="https://www.youtube.com/embed/xxx?rel=0&showinfo=0&autohide=1" width="900" height="450"></iframe>
<div id="video-info"></div>
</div>
<div class="col-sm-4 video-col">
<div class="video-wrapper" onClick="attachSrc('yyy', event)">
<img src="assets/images/thumbnail/yourHeart_official.jpg" width="260" height="160">
<div class="overlay">
<p class="video-title">title 1</p>
<p class="video-author">author 1</p>
</div>
</div>
</div>
<div class="col-sm-4 video-col">
<div class="video-wrapper" onClick="attachSrc('xxx', event)">
<img src="assets/images/thumbnail/yourHeart_karaoke.jpg" width="260" height="160">
<div class="overlay">
<p class="video-title">title 2</p>
<p class="video-author">author 2</p>
</div>
</div>
</div>
<script>
function attachSrc(id, event) {
var text = $(event.target).text();
$('#video-info').append(text);
}
</script>
As you are using jQuery, I would recommend you to use unobtrusive event handler and use .on() to attach event handlers.
Here in example I have attached event with wrapper element and DOM traversal method to traverse and target desired element.
And to persists arbitrary data use data-* prefixed custom attribute which can be fetched using .data(key)
<div class="video-wrapper" data-id="yyy">
Script
$('.video-col').on('click', '.video-wrapper', function() {
var elem = $('#video-info').empty();
var title = $(this).find('.video-title').text();
elem.append(title);
console.log(title);
var author= $(this).find('.video-author').text();
elem.append(author);
console.log(author);
console.log($(this).data('id'));// To fetch custom data associated with element
});
$(function() {
$('.video-col').on('click', '.video-wrapper', function() {
console.clear();
var elem = $('#video-info').empty();
var title = $(this).find('.video-title').text();
elem.append(title);
console.log(title);
var author = $(this).find('.video-author').text();
elem.append(author);
console.log(author);
console.log($(this).data('id')); // To fetch custom data associated with element
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="video-container">
<div id="video-info"></div>
</div>
<div class="col-sm-4 video-col">
<div class="video-wrapper" data-id="yyy">
<img src="assets/images/thumbnail/yourHeart_official.jpg" width="260" height="160">
<div class="overlay">
<p class="video-title">title 1</p>
<p class="video-author">author 1</p>
</div>
</div>
</div>
<div class="col-sm-4 video-col">
<div class="video-wrapper" data-id="xxx">
<img src="assets/images/thumbnail/yourHeart_karaoke.jpg" width="260" height="160">
<div class="overlay">
<p class="video-title">title 2</p>
<p class="video-author">author 2</p>
</div>
</div>
</div>

My Ajax script and event object somehow does not prevent the load

I am currently using AJAX to actually make my website more dynamic. But somehow the event objects method e.preventDefault() does not fire to prevent the link to load. I have specified a container which will be replaced, now I don't know the reason for this failure. Through the .load method I am loading HTML content, to be exact the content from another 'container' in the HTML.
My index.php:
<nav>
<a class = "current" href="index.php">Home</a>
Search
</nav>
<div class="header">
<header class="title">jrr scientists - Official</header>
<img id="logo" height="100" width="160" src="Logo/dev.png">
</div>
<section id="content">
<div id="container">
<div class="img2">
<img id="ish"src="img/ish.jpg">
<img id="mit" src="img/it.png"><br>
<img width="100" height="100" id="home" src="img/toys1.jpg">
<img width="200" height ="100" src="img/This is CS50.gif"> <br><br> <br><br>
<p> This is supposed to be a small thank you to all these institutions to make </p>
<p> education accessable worldwide, even to non-college students. Therefore material </p>
<p> will be pblished here to enhance the use of this education. </p>
<p> *********************************************************************************************** </p>
<p> *********************************************************************************************** </p>
<p> From the Editor JRR - Jayant Raul Rao </p>
</div>
<div id="text">
<p> This is the official website of jrr developer and the </p>
<p> CS environment to make your life easier. This website</p>
<p> will focus on programming and computer science introducing </p>
<p> concepts, displaying offical documentations and scripts </p>
<p> from various examples. We can actually have a look at </p>
<p> Google Scholar pdf's and a lot of facts of cs, maths </p>
<p> and physics undermining the determination and will to </p>
<p> save and keep data in a way to help. This page will be </p>
<p> empowered by different features like a search engine, </p>
<p> CS50 lectures, Google Scholar texts and maths problems. </p>
<p>********************************************</p>
<p> JRR (Jayant Raul Rao) </p>
</div>
<div id="img">
<img class= "img" width="200" height="120" src="img/ibm.jpg">
<img id = "img1" width="190" height="120" src="img/term.png"> <br>
<img id="xcode"width="80" height="70" src="img/xcode.png">
</div>
</div>
</section>
<script type="text/javascript" src="JS/basis.js"></script>
<script type="text/javascript" src="JS/ajax.js"></script>
Now here I will replace the container through this jQuery script (ajax.js)
:
$('nav a').on('click', function(e) { // User clicks nav link
e.preventDefault(); // Stop loading new link
var url = this.href; // Get value of href
$('nav a.current').removeClass('current'); // Clear current indicator
$(this).addClass('current'); // New current indicator
$('#container').remove(); // Remove old content
$('#content').load(url + ' #container').hide().fadeIn('fast'); // New content
});
After this I will load this and replace the old container with the new one:
<!DOCTYPE html>
<html>
<head>
<title>Search</title>
</head>
<body>
<section id = "content">
<div id="container">
<!-- <img src="toys1.jpg" /> -->
<div id="header">
<img class="pio"alt="CS50 Search" src="img/Unknown.gif"/>
</div>
<form action="https://www.google.com/search" method="get">
<input class="t" name="q" type="text"/><br/>
<button class="u">Search</button>
</form>
</div>
</section>
<script type="text/javascript" src="JS/ajax.js"></script>
</body>
</html>
Thank you in advance

Search the document for text to remove more than the tag it's found in

Imagine you had html code like this:
<div id="2761421" class="..." data-attributionline="testtext wrote at..." data-created-at="1342689802000" data-updated-at="1342689802000" data-user-id="36847" >
<div class="subject"> <strong>
<a name="2761421" href="#2761421">wee</a></strong>
</div>
<div class="info">
<div class="author"> author:
<span class="name"> testtext (
we)
</span>
</div>
<div class="date"> date:
<time datetime="dfgdf">dfgdfg
</time>
</div>
</div>
<hr style="clear: both;" />
<div class="text gainlayout"> some text
</div>
<div class="foot gainlayout unselectable">
<span class="menuitem postmenuitem-report">
cvbcvb
</span>
</div>
</div>
What would the javascript code look like that searches the whole document for parts where the div with data-attributionline= contains testtext to replace the whole cited div from start to finish with "Filtered"?
or
What would the javascript code look like that searches the whole document for
<span class="name">
where the name contains testtext to replace the whole div starting from
<div id="<someid>" class="..." data-attributionline="testtext<some text>" data-created-at="<somedate>" data-updated-at="<somedate>" data-user-id="<someid>" >
to the last div, ie
</span>
</div>
</div>
with "Filtered"?
There is a whole bunch of attribute selectors (see also CSS), that will match elements with attributes that start with or contain testtext.
In javascript, you can use document.querySelector[All]() or a library function that supports those to get the elements, then remove them.

Categories

Resources