How to replace text by javascript with other text - javascript

I want to convert
<images src="vendor/chessboard.js/img/chesspieces/wikipedia/wR.png" alt="" class="piece-417db" data-piece="wR" style="width: 67px;height: 67px;"></images>
this text into
<img src="vendor/chessboard.js/img/chesspieces/wikipedia/wR.png" alt="" class="piece-417db" data-piece="wR" style="width: 67px;height: 67px;" />
How can i do so ???

You can use sites like this one to come up with the regex flavor you are after
//Switch <images to <img
var pattern = /<images/gi;//declare your regex pattern
var originString = '<images src="asdf">';//the string to go against
console.log(originString);//show the string as is before modding it
console.log(originString.replace(pattern, "<img"));//show the modded string
//remove </images>
var pattern2 = /<\/images>/gi;
var originString2 = '<img src="blahblah"></images>';
console.log(originString2);
console.log(originString2.replace(pattern2, ""));

Using String.replace to transform <images and ></images> occurrences into <img and /> respectively:
const text = '<images src="vendor/chessboard.js/img/chesspieces/wikipedia/wR.png" alt="" class="piece-417db" data-piece="wR" style="width: 67px;height: 67px;"></images>';
const result = text.replace(/<images/gi, '<img').replace(/><\/images>/gi, '/>');
console.log(result); // -> <img ... />

Related

How to get a substring from Id?

I have the following <img> elements below on different pages. How can I grab all the data-uuid attributes from all using javascript?
It should be able to handle if there is only 1 <img> element or if there are more than 1.
Page foo:
$('[data-uuid]').on('click', function() {
alert($(this).attr('data-uuid'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src='https://placeimg.com/200/200/animals' data-uuid='123'>
<img src='https://placeimg.com/200/200/animals?t=1526063181645' data-uuid='456'>
<img src='https://placeimg.com/200/200/animals?t=1526063190252' data-uuid='789'>
Page bar:
<img src='some-url-5' data-uuid=157>
querySelectorAllMDN and Attribute selector:
let uuids = [...document.querySelectorAll("[data-uuid]")].map(el =>
el.dataset.uuid
);
console.log( uuids )
<img src='some-url' data-uuid=123>
<img src='some-url1' data-uuid=456>
<img src='some-url2' data-uuid=789>
A jQuery version:
var uuids = $("[data-uuid]").get().map(function(el) {
return el.getAttribute("data-uuid");
});
console.log( uuids )
<img src='some-url' data-uuid=123>
<img src='some-url1' data-uuid=456>
<img src='some-url2' data-uuid=789>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
you just have to look for all the img that has a data-uuid attribute
document.querySelectorAll("img[data-uuid]");
something like this

Need to find occurrence of string and replace with another one

I need to parse html string and replace sources of images with it's base64 data.
for example:
input html:
<p>This is some text</p>
<p><img src="sys_attachment.do?sys_id=e57ff4badb984300e330b04ffe9619ce" alt="" width="auto" height="auto" /> </p>
I need to extract sys_id value from src="sys_attachment.do?sys_id=e57ff4badb984300e330b04ffe9619ce" and replace the entire src with it's base64 alternative, to get something like this:
<p>This is some text</p>
<p><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAkEAAAIKCAY....." alt="" width="auto" height="auto" /> </p>
I tried this, but it's not working as expected
var htmlString = '<img src="sys_attachment.do?sys_id=e57ff4badb984300e330b04ffe9619ce"/>';
var res = htmlString.match(/^<img src="sys_attachment.do?sys_id=.*"$/g);
Any ideas how this can be solved?
Get src using htmlString.match(/=.*/)[0].replace("=",'');.
Change it to Base64 using btoa.
var htmlString = '<img src="sys_attachment.do?sys_id=e57ff4badb984300e330b04ffe9619ce"/>';
var sys_id = htmlString.match(/=.*/)[0].replace("=",'');
sys_id = btoa(sys_id);
htmlString = htmlString.replace(/src=\"[^"]*"/,'src="data:image/png;base64,'+sys_id+'"');
console.log(htmlString);

How to make a list of id's or loop using multiple id's in Javascript?

I am trying to find out how to make a list of variables or preferably a loop that identifies the id's. Here is an example.
thumb1 = document.getElementById("image1");
But instead of it being "image1", I want it to go all the way up to image15.
I'd much rather have a loop with the code above that identifies the id's from "image1" to "image15". I am fairly new to Javascript so any help is appreciated! Thank you!
You could do something like this:
var elements = [];
for(var i = 1; i <= 15; i++) {
var id = "image" + i;
elements.push(document.getElementById(id));
}
But the smarter thing to do would be to just add a single class to all of your image elements and use it in combination with querySelectorAll:
var elements = document.querySelectorAll(".image");
<div>
<img id="image1" class="image" />
<img id="image2" class="image" />
<img id="image3" class="image" />
</div>

Random Images, Random Text show after Refreshing

I have these syntax to display random text and image after refreshing the browser. Everything works fine. Please take a look.
JavaScript
var quotes=new Array();
quotes[0] = "text1";
quotes[1] = "Text2";
quotes[2] = "text3";
quotes[3] = "text4";
var q = quotes.length;
var whichquote=Math.round(Math.random()*(q-1));
function showquote(){
document.getElementsByTagName('img')[whichquote].style.display="block";
document.getElementById('quote').innerHTML = quotes[whichquote];
}
showquote();
HTML
<div id="quote"></div>
<div>
<img class="image" src="http://www.placehold.it/100x50&text=1" />
<img class="image" src="http://www.placehold.it/100x50&text=2" />
<img class="image" src="http://www.placehold.it/100x50&text=3" />
<img class="image" src="http://www.placehold.it/100x50&text=4" />
</div>
CSS
.image {
display: none;
}
But later on, I add many more <img scr.../> tags (which are not related to the purpose of this JavaScript) on different places in the page, then the random images didn't show up.
I try a different way by changing document.getElementById to document.getElementByClassName as the syntax below, it doesn't work.
var q = quotes.length;
var whichquote=Math.round(Math.random()*(q-1));
function showquote(){
document.getElementByClass('image')[whichquote].style.display="block";
document.getElementById('quote').innerHTML = quotes[whichquote];
}
showquote();
Then, I try to add an id="imgShow" in each <img..> tag
<div id="quote"></div>
<div>
<img id="imgShow" class="image" src="http://www.placehold.it/100x50&text=1" />
<img id="imgShow" class="image" src="http://www.placehold.it/100x50&text=2" />
<img id="imgShow" class="image" src="http://www.placehold.it/100x50&text=3" />
<img id="imgShow" class="image" src="http://www.placehold.it/100x50&text=4" />
</div>
And instead of document.getElementsByTagName, I change to document.getElementById as below, but the random images don't show, either.
Any idea?
var q = quotes.length;
var whichquote=Math.round(Math.random()*(q-1));
function showquote(){
document.getElementById('imgShow')[whichquote].style.display="block";
document.getElementById('quote').innerHTML = quotes[whichquote];
}
showquote();
I also try to distinguish the random <img src> tags with other <img src> tags inside the page by adding an ID for the parent <div>, then trying to call only the <img> inside that ID, but no success.
HTML
<div id="quote"></div>
<div id="RefreshImg">
<img class="image" src="http://www.placehold.it/100x50&text=1" />
<img class="image" src="http://www.placehold.it/100x50&text=2" />
<img class="image" src="http://www.placehold.it/100x50&text=3" />
<img class="image" src="http://www.placehold.it/100x50&text=4" />
</div>
JavaScript
var q = quotes.length;
var whichquote=Math.round(Math.random()*(q-1));
function showquote(){
document.getElementById('RefreshImg img')[whichquote].style.display="block";
document.getElementById('quote').innerHTML = quotes[whichquote];
}
showquote();
Do you have any idea?
I'd go about it in a slightly different way.
HTML:
<div id='quote'></div>
<img id='quote-img'>
<!-- by giving the img tag an id, we can leave other img tags throughout
the document untouched when we set our random image -->
JavsScript:
var quotes = [
{img: "http://www.placehold.it/100x50&text=1", quote: "text1"},
{img: "http://www.placehold.it/100x50&text=2", quote: "text2"},
{img: "http://www.placehold.it/100x50&text=3", quote: "text3"},
{img: "http://www.placehold.it/100x50&text=4", quote: "text4"}
/*
I've moved the quotes and matching images into objects inside an array
That way, we keep stuff neatly together, and it allows for a great deal
of flexibility when it comes to adding or removing stuff.
*/
];
function showquote() {
var q = quotes.length;
// var whichquote=Math.round(Math.random()*(q-1)); // Logical error...
var whichquote=quote[Math.round(Math.random()*(q-1))]; // ... fixed.
/*
I've moved the quote selection logic into the showquote function.
Again, it allows for more flexibilty: now you could theoretically call
showquote multiple times (maybe through setTimeout for example) and
end up with a different random quote+image each time.
*/
document.getElementById('quote').innerHTML = whichquote.quote;
document.getElementById('quote-img').src = whichquote.img;
};
showquote();
Try something like this:
var quotes = [];
quotes[0] = "text1";
quotes[1] = "Text2";
quotes[2] = "text3";
quotes[3] = "text4";
var q = quotes.length;
var whichquote = Math.floor(Math.random()*q);
function showquote(){
document.getElementById('img'+whichquote).style.display = '';
document.getElementById('quote').innerHTML = quotes[whichquote];
}
showquote();
<div id="quote"></div>
<div>
<img id="img0" style="display:none;" src="http://www.placehold.it/100x50&text=1" />
<img id="img1" style="display:none;" src="http://www.placehold.it/100x50&text=2" />
<img id="img2" style="display:none;" src="http://www.placehold.it/100x50&text=3" />
<img id="img3" style="display:none;" src="http://www.placehold.it/100x50&text=4" />
</div>

Using .next() and .replace() to view images that share similar classes

UPDATE: Here's a jsFiddle, so maybe you can see what I'm trying to accomplish here. I don't think I'm great at explaining myself. http://jsfiddle.net/dh4qx/
I have images in a slideshow I want to be able to view one-by-one using a next or previous button. I can't for the life of me figure out why this function isn't working, or how to make one that does work.
Here's the JS function I'm trying to call when div.next is clicked:
function resNextClick(){
var m = $('#slideshow2 img:visible').attr('class').replace(/\d+/, "");
var $curr = $('#slideshow2 img:visible');
var $next = $curr.next('img.' + m + '/\d+/');
$curr.fadeOut(200);
$next.fadeIn(200);
};
I'm trying to fade the visible image out, and bring up the next image which shares the same class minus the digit. Hope that makes sense.
Here's the HTML:
<div id="slideshow2">
<img class="oc1" src="/Users/justin/Desktop/res-links/oconner1.jpg" />
<img class="oc2" src="/Users/justin/Desktop/res-links/oconner2.jpg" />
<img class="oc3" src="/Users/justin/Desktop/res-links/oconner3.jpg" />
<img class="oc4" src="/Users/justin/Desktop/res-links/oconner4.jpg" />
<img class="el1" src="/Users/justin/Desktop/res-links/salinas1.jpg" />
<img class="el2" src="/Users/justin/Desktop/res-links/salinas2.jpg" />
<img class="el3" src="/Users/justin/Desktop/res-links/salinas3.jpg" />
<img class="el4" src="/Users/justin/Desktop/res-links/salinas4.jpg" />
<img class="el5" src="/Users/justin/Desktop/res-links/salinas5.jpg" />
<img class="el6" src="/Users/justin/Desktop/res-links/salinas6.jpg" />
<img class="el7" src="/Users/justin/Desktop/res-links/salinas7.jpg" />
<img class="el8" src="/Users/justin/Desktop/res-links/salinas8.jpg" />
<img class="ng1" src="/Users/justin/Desktop/res-links/nguyen1.jpg" />
<img class="ng2" src="/Users/justin/Desktop/res-links/nguyen2.jpg" />
<img class="ng3" src="/Users/justin/Desktop/res-links/nguyen3.jpg" />
<div class="img-close">x</div>
<div class="next">next</div>
<div class="prev">prev</div>
</div>
<div class="oc hide">
<div class="desc">
<h3>project: O'CONNER RESIDENCE</h3><br>
<h3>civil engineer: BAI</h3><br>
<h3>project location: CARMEL VALLEY, CALIFORNIA</h3><br>
<h3>dates of my involvement: 06/2006-01/2007</h3><br>
<h3>software: AUTODESK AUTOCAD 2007</h3><br>
<p>This project is typical of the residential projects that I was involved with at BAI. The client was architect IDG of Pacific Grove and BAI provided civil engineering services and project permitting. As drafter and designer, I designed the grading, drainage, erosion control, retaining walls, and underground utilities. The lead engineer approved my design and I then executed about half the drafting, with the balance drawn by others to my redmarks. Following submittal and initial plan check, I also wrote responses to comments from Monterey County Planning, the local fire protection and watershed management districts, the California Department of Water Resources, and the California Coastal Commission.</p><br>
<p>The civil planset as reproduced here was drawn in 09/2006 and submitted for permit in 01/2007.</p>
</div>
<div class="images">
<a href="#">
<div class="back">
BACK
</div>
</a>
<table>
<tr>
<td><img class="oc1" src="/Users/justin/Desktop/res-links/oconner1.jpg" /></td>
<td><img class="oc2" src="/Users/justin/Desktop/res-links/oconner2.jpg" /></td>
<td><img class="oc3" src="/Users/justin/Desktop/res-links/oconner3.jpg" /></td>
<td><img class="oc4" src="/Users/justin/Desktop/res-links/oconner4.jpg" /></td>
</tr>
</table>
</div>
As always, I appreciate all help and feedback.
You are passing RegEx to selector. That is not valid to do!
Try this:
function resNextClick(){
var m = $('#slideshow2 img:visible').attr('class').replace(/\d+/, "");
var $curr = $('#slideshow2 img:visible');
var $next = $curr.next('img[class^="' + m + '"]');
$curr.fadeOut(200);
$next.fadeIn(200);
};
You are doing it wrong, you should use a class for each group of related pictures
<div id="slideshow2">
<img class="oc" src="/Users/justin/Desktop/res-links/oconner1.jpg" />
<img class="oc" src="/Users/justin/Desktop/res-links/oconner2.jpg" />
<img class="oc" src="/Users/justin/Desktop/res-links/oconner3.jpg" />
<img class="oc" src="/Users/justin/Desktop/res-links/oconner4.jpg" />
<img class="el" src="/Users/justin/Desktop/res-links/salinas1.jpg" />
<img class="el" src="/Users/justin/Desktop/res-links/salinas2.jpg" />
<img class="ng" src="/Users/justin/Desktop/res-links/nguyen1.jpg" />
<img class="ng" src="/Users/justin/Desktop/res-links/nguyen2.jpg" />
</div>
And then something like this
function resNextClick(){
var $curr = $('#slideshow2 img:visible'),
cls = $curr.attr('class');
var $next = $curr.next();
// Toggle if next is the same class as this one
if ($next.attr('class') === cls) {
$curr.fadeOut(200);
$next.fadeIn(200);
}
}
You'll need to do an "attribute starts selector"
$curr.next($('*[class^="' + cls.trim() + '"]'))
That should give you the next item that has the same class prefix. I also trimmed the class string due to the extra space.
If the length of the final selector is zero, then you're at the end and should just get the first.
I made simple version of your slideshow (used code form ikaros45 answer as well)
You should be able to use it in your code and I hope it will help you.
Btw I am not sure is it correct way of doing it :)
HTML
<div class="img">
<div class="ox0">1</div>
<div class="ox1">2</div>
<div class="ox2">3</div>
<div class="ox3">4</div>
</div>
jQuery
$(".img div").click(function(){
var selected_img = $(this).attr( "class" ); //get class of clicked element
var group = selected_img.substring(0, selected_img.length - 1);
var set_img = $("#slideshow ."+group);
selected_img = selected_img.substring(2);
var showed = $('#slideshow img:visible');
showed.hide();
$(set_img[selected_img]).show();
$("#slideshow").slideDown();
/*
* for example you clicked on "ox1",
* var group - getting just text part of the class "ox"
* var selected_img - getting just number from class"1"
* var set_img - getting all elements in #slideshow with class "ox"
* $(set_img[selected_img]) - points which big img to open (ox[1])
*/
});
$("#img-next").click(function(){
var curr = $('#slideshow img:visible');
var cls = curr.attr("class")
var next = curr.next();
if (next.attr('class') === cls) {
curr.fadeOut(200);
next.fadeIn(200);
}
else{
var first_img = $("#slideshow ."+cls);
curr.fadeOut(200);
$(first_img[0]).fadeIn();
/*
* getting all elements with same class,
* and showing first
*/
}
});
http://jsfiddle.net/dh4qx/6/

Categories