Consume formatted string into three different elements - javascript

I have code that cuts up a tilte that is formatted like:
TITLE1 - TITLE2 [XXX]
With the three parts getting "parsed" into an array of three pieces and inserted into three div elements:
<div class='title'>
<div class='title2'>
<div class='cut'>
That code is:
var Enumber1 = new Array();
$("#title").each(function(i){
var text = $(this).text();
if(text.indexOf('[') != -1 || text.indexOf(']') != -1){
var Ntext1 = text.split('[')[0];
Enumber1[i] = text.split('[')[1].split(']')[0];
$(this).text(Ntext1);
}
});
$("#cut").each(function(i){
$(this).fadeIn("slow");
if(Enumber1[i] != undefined){
$(this).text(Enumber1[i]);
} else {
$(this).css('N/A');
}
});
So far, I get:
TITLE1 - TITLE2 >>> stay in div class="title"
XXX >>>> cut div class"cut"
What I want is to get this text into:
TITLE1 >>> Stays in <div class"title">
TITLE2 >>> Moves to <div class"title2">
XXX >>> Moves to <div class"cut">
So that the final HTML looks like this:
<div class='title'>
TITLE1
</div>
<div class='title2'>
TITLE2
</div>
<div class='cut'>
XXX
</div>
See https://jsfiddle.net/bro69zvb/6/ for my current code.

You can simply use a split function at the end of your code:
var Enumber1 = new Array();
$(".title").each(function(i){
var text = $(this).text();
if(text.indexOf('[') != -1 || text.indexOf(']') != -1){
var Ntext1 = text.split('[')[0];
Enumber1[i] = text.split('[')[1].split(']')[0];
$(this).text(Ntext1);
}
});
$(".cut").each(function(i){
$(this).fadeIn("slow");
if(Enumber1[i] != undefined){
$(this).text(Enumber1[i]);
}else{
$(this).css('N/A');
}
});
// Get the text from <div class="title>
var titleText = $(".title").text();
//TITLE:
// Get the text before the " - "
title = titleText.split(" - ")[0];
// Put the result inside <div class="title">
$(".title").html(title);
//TITLE2:
// Get the text after the " - " before the next space
title2 = titleText.split(" - ")[1].split(" ")[0];
// Put the result inside <div class="title2">
$(".title2").html(title2);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="title">
Tile1 - Tile2 [XXX]
</div>
<div class="title2">
</div>
<div class="cut">
</div>

Related

How I can create multiple DIVs with ’append’ in jQuery?

I want to loop multiple DIV elements.
There are 5 books. I want to loop 5 books in ID: BootLoop.
What I tried?
my_orders.append(data[i].order.bname).appendTo("#bookLoop > div > div > div > h3");
my_orders.append(data[i].order.blink).appendTo("#bookLoop > div > div > div > a");
It didn't work. Where am I making a mistake?
JS:
var my_orders = $("#bookLoop");
$.each(data, function(i, order) {
$("#bookName").append(data[i].order.bname);,
$("#bookURL").append(data[i].order.blink);
});
HTML (Code structure that should be loop):
<div id="bookLoop">
<div class="col-3">
<div class="block-content">
<div class="d-md-flex">
<h3 id="bookName" class="h4 font-w700"></h3>
<div>
<div class="d-md-flex link">
Details
<div>
<div>
<div>
<div>
JSON:
[
{"order":{"id":"61","bname":"Book 1","blink":984}},
{"order":{"id":"42","bname":"Book 2","blink":5414}},
{"order":{"id":"185","bname":"Book 3","blink":4521}},
{"order":{"id":"62","bname":"Book 4","blink":41254}},
{"order":{"id":"15","bname":"Book 5","blink":7464}}
]
I think that what you want is to append each book and link inside #bookLoop, beign each book and link with it's own content.
Below I'm creating elements (nodes) to each book you have then appending it to my_orders.
Take a look if it is what you want, if not, please edit your question showing an example of the desired rendered HTML
var my_orders = $("#bookLoop");
var books = ''
var links = ''
let data = [
{"order":{"id":"61","bname":"Book 1","blink":984}},
{"order":{"id":"42","bname":"Book 2","blink":5414}},
{"order":{"id":"185","bname":"Book 3","blink":4521}},
{"order":{"id":"62","bname":"Book 4","blink":41254}},
{"order":{"id":"15","bname":"Book 5","blink":7464}}
]
$.each(data, function(i, order) {
let col = document.createElement('div')
col.className = 'col-3'
let content = document.createElement('div')
content.className = 'block-content'
let flexC = document.createElement('div')
flexC.className = 'd-md-flex'
let title = document.createElement('h3')
title.className = 'h4 font-w700'
title.textContent = data[i].order.bname;
flexC.append(title)
let flexL = document.createElement('div')
flexL.className = 'd-md-flex link'
let details = document.createElement('a')
details.className = 'bookURL'
details.href = "#"
details.textContent = "Details: " + data[i].order.blink
flexL.append(details)
my_orders.append(col)
col.append(content)
content.append(flexC)
content.append(flexL)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="bookLoop">
<div>

First and second name initials, preserving full surname

It's my first touch with javascript and I really need help. I have an html with divs containing from one to three "author" text values each. I need to make automate shorting the names (only first names) if there is more than one "author" in div.
Eg.
<div class="book">
<a> <h2>Book 1</h2>
<h3 class="author">Minty Estelle</h3>
<h3 class="author">Katey Josepha Shevon</h3></a></div>
<div class="book">
<a> <h2>Book 2</h2>
<h3 class="author">Leila Seward</h3></a></div>
So that output would be:
Book 1
M. Estelle
K.J. Shevon
Book 2
Leila Seward
So if there is only one "author" - his name stays unchanged. But if it's more than one - firstname and secondname (but not surname - last value) is shortened to first leter and followed by dot.
I searched a lor and played with compilations... but nothing worked. Is anyone can help to find a solution?
My js so far is:
var authorName = $(".book h3");
authorName.each(function(){
if(authorName.length > 1 && authorName.hasClass("author")){
var names = authorName.split(" ");
var shortened = names.not(:lastChild).map(s => s.slice(0, 1).append(". "));
document.authorName.innerHTML = shortened;
}
You'll have to loop over your books, then loop over every author of said book :
//For each book
$('.book').each(function() {
//If the book has more than one author
if ($('h3.author', this).length > 1) {
//For each author
$('h3.author', this).each(function() {
//Store the author name before emptying it
var words = $(this).text().split(' ');
$(this).text('');
//For each word inside the author name
for (var i = 0; i < words.length; i++) {
//If it's not the last name
if (i < words.length - 1) {
//Only keep the first letter
$(this).text($(this).text() + words[i].substring(0, 1) + '. ');
//Else keep the whole word
} else $(this).text($(this).text() + words[i]);
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="book">
<a>
<h2>Book 1</h2>
<h3 class="author">Minty Estelle</h3>
<h3 class="author">Katey Josepha Shevon</h3>
</a>
</div>
<div class="book">
<a>
<h2>Book 2</h2>
<h3 class="author">Leila Seward</h3>
</a>
</div>
This is a simple version, Adjust it for your own needs, and maybe refactor it to be more in functional way :)
/*
So that output would be:
Book 1
M. Estelle
K.J. Shevon
Book 2
Leila Seward*/
$(".book").each(function() {
var authors = $('h3.author', this);
if (authors.length > 1) {
authors.each(function() {
var result = $(this).text().split(' ').map(function(name, index, arr) {
return index < arr.length - 1 ? name[0]+'.' : name;
}).join(' ');
$(this).text(result);
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
<div class="book">
<a> <h2>Book 1</h2>
<h3 class="author">Minty Estelle</h3>
<h3 class="author">Katey Josepha Shevon</h3></a></div>
<div class="book">
<a> <h2>Book 2</h2>
<h3 class="author">Leila Seward</h3></a></div>

How can I get the matched element's parent div attribute by regular express using Javascript

Have a html string see below.
<div sentence="11">
<p>
how are you Tom, how are you Tom
</p>
</div>
<div sentence="12">
<p>
how are you Tom
</p>
</div>
When user select the name 'Tom', I will replace the string 'Tom' using a name tag with some html style. The result what I want see below.
<div sentence="11">
<p>
how are you <span class="ano-subject" data-oristr="Tom" data-offset="1" data-sentence="11"><NAME></span>, how are you <span class="ano-subject" data-oristr="Tom" data-offset="2" data-sentence="11"><NAME></span>
</p>
</div>
<div sentence="12">
<p>
how are you <span class="ano-subject" data-oristr="Tom" data-offset="1" data-sentence="12"><NAME></span>
</p>
</div>
I will using the code below to do the replace.
var content = HTML CODE ABOVE;
var selectText = 'Tom';
var regex = new RegExp('(?=\\s|^|\\b)(?:' + selectText + ')(?=\\s|$|\\b)', "g");
var pre_sentence = 0;
var offset = 0;
content = content.replace(regex, function(match, position) {
var curr_sentence = ???; // how can I get this element's parent div attribute 'sentence' ?
if(pre_sentence != cur_sentence){
// this is new sentence.
offset = 1;
pre_sentence = curr_sentence;
} else {
offset++;
}
var replace = '<span class="ano-subject" data-oristr="Tom" data-offset="'+offset+'" data-sentence="'+curr_sentence+'"><NAME></span>';
return replace;
});

Displaying results, in different div's from a JavaScript loop

var parseResponse = function() {
var data = JSON.parse(this.response);
console.log (data);
var head = "Cheapest Flight to " + document.getElementById('search_term1').value;
var bodystuff = document.createElement('h4');
bodystuff.innerHTML = head;
document.getElementById('right1').appendChild(bodystuff);
for (var i=0; i<data.results.length; i++) {
try {
var printDeparture = "Depart: " +
data.results[i].itineraries[i].outbound.flights[i].departs_at;
var bodystuff = document.createElement('p');
bodystuff.innerHTML = printDeparture;
document.getElementById('right1').appendChild(bodystuff);
console.log(printDeparture);
} catch (err) {
console.log(data.results[i]);
}
}
}
I am trying to get each result printed out in a separate div (currently, I have 3 results back) but can only print out the first of the three, I have tried to increase [i] in each of the results, and changed the divs from "right1" to "left1" but nothing happens. any help?
Here is my HTML code;
<div class="wrap">
<div class="left">
<img src="Assets/China.png" class="pics">
</div>
<div class="right" id="right1">
</div>
</div>
<div class="wrap">
<div class="left" id="left1">
</div>
<div class="right" >
<img src="Assets/hotel.jpg" class="pics">
</div>
</div>
and here is the result I get back from the API:
Object
results
:
Array[3]
0
:
Object
1
:
Object
2
:
Object
(hope it makes sense)

How to get text from span->li->ul-> Element

Hello i have cart full with Elements
This Ex of one of them
<div class="item-container cart-item">
<div>
<img border="0" onerror="src='http://www.myengravedjewelry.com/Admin/surfing.jpg'" title="Bloody Mary Style Colour Name Necklace" src="http://www.myengravedjewelry.com/Admin/surfing.jpg" alt="1009">
<div class="item-header">
<div class="item-body">
<ul class="item-ul">
<li>
<li>
<li>
<span class="bold-14">Price:14.9 </span>
</li>
<li>
<span>ShortId:1010 </span>
</li>
<li>
<span>LongId:110-01-073-10 </span>
</li>
<li>
<span class="spanDefCat">DefaultCat:334 </span>
</li>
</ul>
</div>
</div>
<div class="item-footer"></div>
</div>
When i press save i go trow each one of this element and check if DefaultCat==0
var elements = document.getElementsByClassName("cart-item");
and i try to get to this defaulCat like this
for(i=0;i<elements.length;i++){
var elementContent=elements[i].find(".spanDefCat").html();
var vars = elementContent.split(" ");
var obj = {};
vars.forEach(function(v) {
var keyValue = v.split(":");
obj[keyValue[0]] = keyValue[1];
});
DefaultCat = obj["DefaultCat"];
ShortId = elements[i].children[1].alt;//New style to take ShortID
if(DefaultCat==0)setDefaultCatToProductId(parseInt(ShortId));
arrSortedOrder[i]=parseInt(ShortId);
}
Any one know how to get to this value?
p.s
Plz Do NOT give me solution with $(.spanDefCat) because when i find deff=0 i need to take ShordId as Well from this element[i]
Try this:
$(".cart-item").each(function(){
var shortId = $(this).find(".bold-14").parent("li").siblings("li").children("span").html();
var shortItem = shortId.replace(' ','').split(":");
var defaultCat = $(this).find(".spanDefCat").html();
var item = defaultCat.replace(' ','').split(":");
if(item[1]==0){
var id = parseInt(shortItem[1]);
//do something
}else{
var id = parseInt(shortItem[1]);
//do something else
}
console.log(defaultCat);
console.log(shortId);
});
Note: Above code give you the DefaultCat:334 and ShortId:1010 so now you can use both in if else statement.
If the format of DefaultCat:334 is same for all cart item then you can check whether it is 0 or not
JSFIDDLE DEMO
I see JQuery tag so i give you a response with JQuery statements.
$(".cart-item").find(".spanDefCat").each(function(index, domEle){
//get text, delete spaces and split
split_result = $(domEle).text().replace(' ','').split(":");
//get only numeric value as string
defaultCat = split_result[1];
//parse into int
defaultCat = parseInt(defaultCat);
//if your var is equal to 0
if(defaultCat == 0){
/*********************
* Type you code here *
**********************/
}
});

Categories

Resources