How to slice specific characters in every item of an array - javascript

I'm trying to bold the first four characters of every item of an array (in this case a list), but all I know how to do is select whole strings:
$("li").slice(0).css("font-weight", "Bold");
How can I specify which of each string's characters I want to slice?

$('li').each(function() {
var $li = $(this);
var txt = $li.text();
$li.text(txt.substring(4));
$li.prepend($('<b/>').text(txt.substring(0,4)));
});
That iterates through each <li> tag and replaces the inner text with a bold tag containing the first four characters, and the remaining original text afterwards.
You could switch the <b> to a <span> to have more control over the style. You could also experiment with .html() if you need to preserve other markup within each list item.

Here is an example which may help you:
$("li").each(function() {
var len = $(this).text().length,
text1 = $(this).text().slice(0, 4),
text2 = $(this).text().slice(5, len);
$(this).html('<b style="color:red">' + text1 + '</b>' + text2);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>how-to-slice</li>
<li>specific</li>
<li>characters</li>
<li>in-every</li>
<li>item-of-an-array</li>
</ul>

Related

Clear formatting in range without using document.execCommand('removeFormat')

I want to allow a user to select, create a range, and then have javascript remove the underline on the range that the user selects. For example, If I have the code
<u> Hello, my name is Justin, and I have a question </u>
And the user selects "Justin, and I" and hits un-underline, would it be possible to change the HTML to:
<u> Hello, my name is </u>
Justin, and I
<u> have a question </u>
or if the entire sentence is selected, have the entire element deleted and replaced with normal text?
The solution has bugs if selected both underline and normal text at same time, i am trying to fix it.
getSelection() to get selected text.
getRangeAt(0) get selected index in string, remember to +3 because the length of <u> is 3.
Use slice() create new html and replace the old html.
function selected() {
let target = document.getSelection(),
range, res
if (target.toString() === '') return
range = target.getRangeAt(0)
if (range.commonAncestorContainer.parentElement.tagName != 'U') return
res = range.commonAncestorContainer.parentElement.outerHTML
let head = res.slice(0, range.startOffset + 3),
middle = `</u>${target.toString()}<u>`,
tail = res.slice(range.endOffset + 3)
range.commonAncestorContainer.parentElement.outerHTML = head + middle + tail
}
document.onmouseup = selected;
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<u>Hello, my name is Justin, and I have a question</u>
</body>
</html>

Get text between tags using javascript

I am trying to get prices from between span tags. I would like to have all prices in an array. I cant seem to get it to work, I am guessing my regex is incorrect.
I am looking for any span tags with the class 'amount', the tag has no other attributes set and only has one class. E.g. <span class="amount">£9.99</span>
var prices = resp.fragments['data'].match(/<span class=\"amount\">(.*?)<\/span>/g)
.map(function(val){
return val;
});
Output
[ '£9.99', '£100.00' ]
I am trying to get prices from between span tags. I would like to have all prices in an array. I cant seem to get it to work, I am guessing my regex is incorrect.
I am looking for any span tags with the class 'amount', the tag has no other attributes set and only has one class. E.g. <span class="amount">£9.99</span>
var prices = resp.fragments['data'].match(/<span class=\"amount\">(.*?)<\/span>/g)
.map(function(val){
return val;
});
Output
[ '£9.99', '£100.00' ]
* UPDATE *
Turns out it was an encoding with the ajax response resp.fragments['data'].
I was using regex as it is something I have not really used before in JS and thought I would have a play. I did look at many examples and after about 45 mins with no success I thought a fresh set of eyes would fix it.
#spaceman
Thanks for the helpful comment. Your one of those people if someone asked "Is there is a doctor in the house?", you would stand up and say "Sweet load there are loads of doctors out there".
While a regular expression could work for this, it might be easier to simply select the <span class='amount'> elements and map their innerHTML content to an array via the map() function:
// This would yield an array containing your values
var amounts = Array.prototype.slice
.call(document.querySelectorAll('span.amount'))
.map(function(a){ return a.innerHTML; });
You can see a working example of this demonstrated here.
Simplest method will be to add this to an invisible DOM object and then traverse it via DOM API
var text = '<span class="amount">£9.99</span><span class="amount">£9.99</span>'
//now append it to an DOM object
var wrapperDiv = "<div style='display:none' id='tmpDiv'>" + text + "</div>";
document.body.innerHTML += wrapperDiv;
var elements = document.querySelectorAll( "#tmpDiv amount" );
var output = Array.prototype.slice.call( elements ).map( function(val){
return val.innerText;
})
Another approach could be split the text by <span class="amount"> and get the value after first index
DEMO
var text = '<span class="amount">£9.99</span><span class="amount">£9.99</span>'
var output = [];
text.split('<span class="amount">').forEach( function(val, index) {
if (index > 0 )
{
output.push( val.replace( "</span>", "" ) );
}
});
document.body.innerHTML += JSON.stringify( output, 0, 4 );
You can use this instead.
var prices = document.getElementsByClassName('amount');
var price_array = [];
for (i= 0; i < prices.length; ++i) {
price_array.push(prices[i].innerHTML);
}
document.write(" | " + price_array);
<span class='amount'>£123</span>
<span class='amount'>£3</span>
<span class='amount'>£5</span>
<span class='amount'>£64</span>
You don't need to use regex or jQuery for this.

insert string at index ignoring html tags

Is it possible to insert a string, in my case <br> at a specific index ignoring HTML tags ?
I have <span style="font-family:Arial;font-size:14px">Here is my text</span>
Is it possible to add the after HER , or any other solution is welcomed
It should look : <span style="font-family:Arial;font-size:14px">Her<br>e is my text</span>
Edit:
I need to call a function like :
insertBR(htmlContent,3)
Something rather simple with some jquery and string replacement.
/*
Gets the text of the element then matches every 3 letters into an array then joins them with <br>
*/
var text = replaceText($('span').text(), 3);
$('span').html(text);
function replaceText(string, index) {
return string.match(new RegExp(".{1," + index + "}", "g")).join('<br>')
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<span>Here is my text</span>
EDIT
Added index

How to add <br/> tag dynamically in <p> tag

I have written html as below lines of code.
<div class="da-slide">
<h2><i><asp:Label ID="lblHeading3" runat="server"></asp:Label></i></h2>
<p>
<i><asp:Label ID="lblDescription3" runat="server"></asp:Label> </i>
</p>
<div class="da-img">
<img src="../img/bg/html5andcss3.png" alt="image01" />
</div>
</div>
Now I want to add br tag inside p tag after every four words dynamically.
Please help me!!!
I don't think this is the best approach; however you could achieve this using split, mod and join
// find all <p> elements in the 'da-slide' using jQuery and loop through each instance
$('p', '.da-slide').each(function(p_i, p_el){
// get the text for this <p> element
var txt = $(p_el).text();
// split the text into individual words (assume separated by space)
var txt_split = txt.split(' ');
// every 4th word place a <br>
var txt_tokenized = [];
txt_split.forEach(function(string, index){
if (parseInt(index) % 4 == 0){
txt_tokenized.push('<br/>');
}
txt_tokenized.push(string);
});
// rebuild as html
$(p_el).html(txt_tokenized.join(' '));
});
Relying on this answer on how to get all the words of a specific text-node you can try the following:
var res = $('.da-slide p *').contents().map(function () {
if (this.nodeType == 3 && this.nodeValue.trim() != "") //check for nodetype text and ignore empty text nodes
return this.nodeValue.trim().split(/\W+/); //split the nodevalue to get words.
}).get(); //get the array of words.
var new_content = [];
$.each(res, function(index, value){
index++; // avoid the modulo operation with index 0
if(index % 4 === 0){
new_content.push(value + '<br/>'); //add a break after every 4th word
}else{
new_content.push(value);
}
console.log(new_string);
});
$('.da-slide p i').html(new_content.join(' ')); //concatenate the new content with whitespaces
Demo
Reference
.contents()
.map()
.get()
.each()
Node

add what contains in element along with array

I'm trying to add the content of each span along with the value in the title attribute.
<div id="group-wrap" class="group">
<span class="lbracket" title="&f">(</span>
<span class="grouptitle" title="&f"> Group </span>
<span class="rbracket" title="&f">) </span>
<span class="username" title="&f"> Username </span>
<span class="col" title="&f">:</span>
<span class="text" title="&f"> Helo There! </span>
</div>
Here is what I have so far:
var str = [];
$('#group-wrap span').each(function(){
str.push($(this).attr('title'));
});
alert(str.join(''));
});
http://jsfiddle.net/B9QeK/3/
The output is &f&f&f&f&f (the value of each title attribute), but the expected output has the value, plus the content that is in the span. The value of the attribute should be appended before the content.
&f(&fGroup&f)&fUsername: &f text
How can I get this result?
Looks like you are looking for
str.push( this.getAttribute('title'), this.textContent || this.text );
As for performance reasons, you should not re-create a jQuery object for every single iteration. Even better, don't use jQuery at all to receive those values.
JSFiddle
And by the way, you can make usage of jQuerys .map() to do it a bit more elegant:
jQuery(function($){
var str = $('#group-wrap span').map(function(){
return this.getAttribute('title') + this.textContent || this.text;
}).get();
alert(str.join(''));
});
JSFiddle
Reference: .map()
jQuery(function($){
var str = [];
$('#group-wrap span').each(function(){
str.push($(this).attr('title') + $(this).text());
});
alert(str.join(''));
});
Working JSFiddle
text:
Description: Get the combined text contents of each element in the set of matched elements, including their descendants.
docs
Just use the text method to get the text content of each span:
var str = [];
$('#group-wrap span').each(function(){
//Push value of title attribute and text content into array:
str.push($(this).attr('title') + $(this).text());
});
alert(str.join(''));
});
Your line
str.push($(this).attr('title'));
Should look like:
str.push($(this).attr('title') + $(this).text());
Although, this is making two identical calls $(this), so you might consider caching:
var $this = $(this)
str.push($this.attr('title') + $this.text());
var str = "";
$('#group-wrap span').each(function(){
str+=$(this).attr('title')+$(this).text();
});
alert(str);
});

Categories