Used below HTML & JS to get first character of string and display. Manually its possible to calculate and get value.
When its goes to dynamic and name with only first and last name not sure how to calculate character position after space and get first character of word.
$('.splitname .fname').html(name.charAt(0));
$('.splitname .mname').html(name.charAt(8));
$('.splitname .lname').html(name.charAt(16));
<div class="name">Desmond Patrick Reymond</div>
<div class="splitname">
<span class="fname">D</span>
<span class="mname">P</span>
<span class="lname">R</span>
</div>
Use this logic:
"Desmond Patrick Reymond".split(" ").map(name => name[0])
// => ["D", "P", "R"]
If you need to modify the HTML programmatically, do:
let s = $('.name').text();
s.split(" ").map(name => $('.splitname').append(name[0]))
(It's not really good practice to use map for side effects though; you may choose to use forEach instead.)
You can simply use match() function and a simple ReGex to get the dynamic text data with spaces without having to check for charAt()
//get text
let name = $('.name').text();
//match the spaces
var matches = name.match(/\b(\w)/g); // [D,P,R]
//join the chars - if needed
var joinChar = matches.join(''); // DPR
//show the split name
$('.splitname').text(joinChar);
console.log(matches ) // [D,P,R] //Array
console.log(joinChar) //DPR //String
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="name">Desmond Patrick Reymond</div>
<div class="splitname"></div>
You can make use of Array#split and Array#map and Array#join as in the demo below. Result will be:
<div class="splitname">
<span class="fname">D</span>
<span class="mname">P</span>
<span class="lname">R</span>
</div>
//Classes for the initials
const classes = ['fname', 'mname', 'lname'];
//Where to put the initials
$('.splitname')
//make HTML generated content of
.html(
//Get Full Name
$('.name').text()
//Break into names array
.split(' ')
//Get initial of each name
.map(name => name.charAt(0))
//Wrap each initial in a span element
.map((initial,index) => `<span class="${classes[index]}">${initial}</span>`)
//Join all span elements array into string
.join('')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="name">Desmond Patrick Reymond</div>
<div class="splitname"></div>
Related
I have the below url
<h1 id="header_2" title="mytitle" data-id="header_title" class="sampleclass " xpath="1">mytitle<span aria-label="sometest" class="sampleclass ">- Saved</span></h1>
Based in the id(header_2)I wabt to fetch title.
My id may also contains like this id="header_mdfa3fad" but for sure after "_" it is numeric.HOw do I write querySelector for it
You can apply regex to filter like this
var divs = [].slice.call(document.querySelectorAll("[id^='header_']")).filter(function(el){
return el.id.match(/^header_[0-9]+/i);
});
console.log(divs);
<div id="header_1"></div>
<div id="header_2"></div>
<div id="header_3"></div>
<div id="header_abc"></div>
<div id="header_xyz"></div>
You can use this solution:
const headers = document.querySelectorAll("[id^='header_']");
const titles = [];
headers.forEach((header) => titles.push(header.getAttribute('title')));
// Do something you want with titles array
If I understand you correctly, try something like this:
#select h1 elements with id attribute whose value begins with "header"
headers = document.querySelectorAll("[id^='header_']");
#loop through the elements and extract the part of the attribute value following "_"
for (let header of headers) {
target = header.getAttribute('id').split('_')[1]
#check for the presence of a digit
if (/\d/.test(target)) {
console.log(header.getAttribute('title'))
}
}
I need to remove the text 'at' from this title.
<p>Marge Makes Pancakes Email at</p>
The text in this title is dynamically created so I can't change the whole thing.
I tried using this but it doesn't work.
<script>var elements=document.getElementsByClassName("spotlight__title");elements[0].innerHTML=elements[0].innerHTML.replace(/at/g,"");</script>
You need to iterate over collection returned from getElementsByClassName.
var elements = document.getElementsByClassName("spotlight__title");
Array.from(elements).forEach( element =>
element.innerHTML = element.innerHTML.replace(/at/g,"")
)
You can use querySelectorAll to find all elements by using a CSS Selector and then iterate over them to replace text according to your regex.
function replaceText(target, re, newText) {
document.querySelectorAll(target).forEach(function(element) {
element.textContent = element.textContent.replace(re, newText).trim();
});
}
replaceText('.spotlight__title', /at$/g, '');
<p>
Marge Makes Pancakes Email 1 at
</p>
<p>
Marge Makes Pancakes Email 2 at
</p>
<p>
Marge Makes Pancakes Email 3 at
</p>
I have created a simple program that filters words based on a list from an external txt file with regex inside my js file.
For the most part when I input a list of words from the txt file they are filtered out. However there is one keyword that is causing me trouble.
'black & decker'
I am guessing it has to do with the '&' sign because any new words I put into the txt file with a '&' sign does not filter out for some reason.
Can anyone help me to why words with the & is not filtering out properly? And also check if my regex is written properly for this program(var filtered)?
Any help would be much appreciated. Thank you.
I have a list of words in a txt file here:
baby bullet, baby-bullet, back2life, back-2-life, black & decker, black-decker, black-&-decker, britax, bose, capital brands products, capital-brands-products, dewalt, dyson, ergobaby, ergo-baby, fiskars, ickle bubba, ickle-bubba, kitchen aid, kitchen-aid, longstem, long-stem, magic bullet, magic-bullet, makita tools, makita-tools, milwaukee, monster cable, monster-cable, mustee, nest, nutri____, nutribullet, oxo, party bullet, shark, simplehuman, sony bravia, urban decay, urban-decay, waterpik, weber grill, weber-grill, youthology, teeter
Here is my JS file that filters inputted words based on the txt list
// This grabs the data from the txt file and splits each word by commas
$.get('word-list.txt', function(data) {
pbfFilterWords = data.split(', ');
pbfFilterWords.forEach(function(word){
pbfWordList = word;
});
// This defines a global variable so the filter button has a list of words to filter with
var pbfWordList = pbfFilterWords;
//This will allow the list of words to filter with regex
var pbfRegEx = pbfFilterWords;
var filtered = (function(){
var filtered = [], i = pbfRegEx.length;
while (i--) {
if (/w*[\s|\w|\b+]*\w*/.test(pbfRegEx[i])) {
filtered.push(pbfRegEx[i]);
}
}
return filtered;
})();
console.log(filtered.join());
// Function for filter button
$('.pbf-link-container[contenteditable]').html;
$('#pbf-filter').click(function(){
var $pbfOutput = $('.pbf-link-container[contenteditable]').html();
// Array of words for filter
var pbfFilterWords = pbfWordList;
// Output to new DIV and remove specified keywords from pbfFilterWords
$('.pbf-link-output').html($pbfOutput);
// To make pbfFilterWords not case sensitive
$.expr[":"].contains = $.expr.createPseudo(function(arg) {
return function( elem ) {
return $(elem).html().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
};
});
// Function to output the filtered words
$.each(pbfFilterWords , function(i , filtered){
$('.pbf-link-output > div:contains("'+filtered+'")').remove();
});
});
});
Here is my html:
<div id="pbf-container">
.....
<div class="pbf-link-container" contenteditable="true">
<div><br/></div>
</div>
<div class="pbf-button-control">
<button id="pbf-filter"> Filter </button>
</div>
<div class="pbf-filter-header">
<h3> Filtered Links </h3>
</div>
<div class="pbf-link-output">
</div>
</div>
Your pseudo selector implementation takes html version of inner contents of the div tag, so it converts & to & and you don't have a match.
You can see yourself:
$.expr[":"].contains = $.expr.createPseudo(function(arg) {
return function( elem ) {
// console.log value of current element here
console.log($(elem).html().toUpperCase()); // logs string with &
return $(elem).html().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
};
});
use $(elem).text() to get text version of inner content of a div.
I am trying to create a function that takes two parameters, a number and a string. I need to be able to call it with a number, n, so that the nth element of theList will be modified to read as the string from the function.
I am a BEGINNER, so I am struggling with this -- I know that what I currently have in the function is NOT what I need, but I was hoping to use it as a starting point that I could adapt. I am thinking I probably need to use looping to do this...beyond that, I dont have many ideas. Any guidance?
<html>
<script>
function doit() {
document.getElementById('element1').innerHTML='Element one';
document.getElementById('element2').innerHTML='Element two';
document.getElementById('element3').innerHTML='Element three';
}
</script>
<body>
<p>Value: <input type="text" id="theInput" value="" size=10>
<input type="button" id="theButton" value="click me!" onclick="doit()"></p>
<ul id="theList">
<li id="element1">Element 1
<li id="element2">Element 2
<li id="element3">Element 3
</ul>
<div id="theDiv"></div>
</body>
</html>
You can use jQuery to get the children (li) element of the ul tag. It will return an array of all of the children. Note, the array is zero-indexed. You will need to keep this in mind when passing index in, or update the code to -1 from the index.
function updateListItem(index, text) {
var myListItem = $("#theList").children()[index]; // DOM reference to the list item
$(myListItem).text(text); // update the text
}
Without jQuery, you can do it something like this:
function updateListItem(index, text) {
var myListItem = document.getElementById("theList").children[index] // An array of the list items
myListItem.innerHTML = text; // update the text
}
Here are some ideas as to what you should do:
For function doit, you need to add two parameters representing the string and the number.
Next, create a variable that is the concatenation (string addition) of "element" and your number parameter
Finally, use your above method to set document.getElementById(<your string here>) to whatever your string was.
Here is an example of a quick implementation:
function doit(str, num){
var elementID = "element" + num;
document.getElementById(elementID).innerHTML = str;
}
I have an unordered list called test
<ul id='test'></ul>
it is dynamically populated with data via ajax. Each item 'li' is a div containing 'p' paragraphs. Each paragraph contains some information.
Ex:
<li> <div> <p> test </p> </div> </li>
<li> <div> <p> hi how is it going?</p> </div> </li>
<li> <div> <p> not a test</p> </div> </li>
<li> <div> <p> whoa</p> </div> </li>
I also have a search box which i can get a search term from, I use:
var searchTerm = $("#search").val().trim().split(' '); // an array of words searched for
What I am trying to do is find a way to select all 'li' elements which contain all or some of the search words, but I'm not sure how to approach it best.
Currently, I am doing this:
var results = $('p:contains("'+ searchTerm[0] +'")');
to get an exact match on the first term, but I want to search for multiple terms, not just one.
I would want to search for 'test hi' and get back three nodes cause it searches for 'test' and 'hi'.
I also thought of:
var results2 = $('p').filter(function( index ) {
return ( this +':contains("'+ searchTerm +'")' );
});
Anyone point me in the right direction?
You could do some black magic with the selector, like this:
var results = $('p:contains("' + searchTerm.join('"), p:contains("') + '")');
This looks hard, but I'll explain it.
It joins the search terms with "), p:contains(". Then it just adds the missing p:contains(" and ") to the ends of the result string and searches for it.
A combination of $.filter and $.each (or array.forEach, if you don't care about ie8) can also be of use here:
var searchTerms = ["how", "test"];
$('div').filter(function () {
$text = $(this).text();
var found = 0;
$.each(searchTerms, function (index, term) {
found = $text.indexOf(term) > -1 ? found +1 : found;
})
return found;
}).addClass('match');
jsFiddle