I have a div with some content in four lines. I am able to get number of lines by using the following code. But my requirement is to get 4 line text of the div. For example:
<div>
ut returns between paragraphsut returns between paragraphs
ut returns between paragraphsut returns between paragraphs
web ui text is going on hereut returns between paragraphsut
returns between paragraphs
</div>
In the above DIV.I want to get 4th line text i.e., returns between paragraphs.Is there any way to do this.
I am getting number of lines with the following code
var content = elm.innerHTML;
var elmHeight = elm.offsetHeight;
var lineHeight = 15;
var lines = elmHeight / lineHeight;
lines variable has number of lines in a particular DIV
var line_number=3; // The line number you prefer
var result= $.trm( $( '#mydiv' ).text() ).split( '\n' )[line_number];// mydiv is the id of division
alert(result);
The following works in Firefox for me. I hope it could be adopted to work under IE as well.
<html>
<head>
<script language="javascript">
<!--
function find3rdline (element)
{
var text = element.textContent;
var begin = -1;
var end = -1;
var top = -1;
var line = -1;
for (i = 0; i < text.length; i++)
{
var id = "marker" + i;
element.innerHTML = text.substr (0, i) + "<span id='" + id + "'>X</span>" + text.substr (i, text.length - i);
var marker = document.getElementById (id);
if (marker.offsetTop != top)
{
top = marker.offsetTop;
line++;
if (line == 2) begin = i;
else if (line == 3)
{
end = i;
// break;
}
}
}
element.innerHTML = text;
if (begin == -1) return "";
else if (end == -1) return text.substr (begin, text.length - begin);
else return text.substr (begin, end - begin);
}
// -->
</script>
</head>
<body onload="alert ('Third line is: [' + find3rdline (text) + ']')">
<div id="text">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce porttitor, leo non sollicitudin blandit, metus eros dapibus massa, nec euismod nunc sapien quis nunc. Maecenas mollis, justo sed egestas semper, nulla libero blandit sem, eget gravida ante sapien sagittis turpis. Vivamus sit amet elit tortor, a eleifend mi. Aliquam erat volutpat. Vestibulum sit amet pellentesque magna. Integer eget erat nisl. Suspendisse adipiscing placerat felis quis blandit. Etiam hendrerit tincidunt gravida. Nunc condimentum tristique commodo. Aliquam eget tellus et sapien accumsan cursus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce porttitor, leo non sollicitudin blandit, metus eros dapibus massa, nec euismod nunc sapien quis nunc. Maecenas mollis, justo sed egestas semper, nulla libero blandit sem, eget gravida ante sapien sagittis turpis. Vivamus sit amet elit tortor, a eleifend mi. Aliquam erat volutpat. Vestibulum sit amet pellentesque magna. Integer eget erat nisl. Suspendisse adipiscing placerat felis quis blandit. Etiam hendrerit tincidunt gravida. Nunc condimentum tristique commodo. Aliquam eget tellus et sapien accumsan cursus.
</div>
</body>
</html>
Related
can someone please help me & explain this example for the pageYOffset?
var frame = document.getElementById("frame");
var frameDoc = frame.contentDocument;
var info = document.getElementById("info");
var target = frameDoc.getElementById("overview");
frameDoc.scrollingElement.scrollTop = target.offsetTop;
info.innerText = "Y offset after scrolling: " +
frame.contentWindow.pageYOffset + " pixels";
https://developer.mozilla.org/en-US/docs/Web/API/Window/pageYOffset
I'm trying to apply it to on my page but it doesn't work.
I'm getting this error:
app.js:23 Uncaught TypeError: Cannot read property 'getElementById' of undefined
at app.js:23
JavaScript
// Get the offset position of the navbar
const allSections = document.querySelectorAll("allSections");
const allSectionsDoc = allSections.contentDocument;
const section = allSectionsDoc.getElementById("section1");
allSectionsDoc.scrollingElement.scrollTop = section.offsetTop;
section.innerText = "Y offset after scrolling: " +
allSections.contentWindow.pageYOffset + " pixels";
HTML
<div id="allSections">
<section id="section1" data-nav="Section 1" class="your-active-class section">
<div class="landing__container active">
<h2>Section 1</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi fermentum metus faucibus lectus pharetra dapibus. Suspendisse potenti. Aenean aliquam elementum mi, ac euismod augue. Donec eget lacinia ex. Phasellus imperdiet porta orci eget mollis. Sed convallis sollicitudin mauris ac tincidunt. Donec bibendum, nulla eget bibendum consectetur, sem nisi aliquam leo, ut pulvinar quam nunc eu augue. Pellentesque maximus imperdiet elit a pharetra. Duis lectus mi, aliquam in mi quis, aliquam porttitor lacus. Morbi a tincidunt felis. Sed leo nunc, pharetra et elementum non, faucibus vitae elit. Integer nec libero venenatis libero ultricies molestie semper in tellus. Sed congue et odio sed euismod.</p>
<p>Aliquam a convallis justo. Vivamus venenatis, erat eget pulvinar gravida, ipsum lacus aliquet velit, vel luctus diam ipsum a diam. Cras eu tincidunt arcu, vitae rhoncus purus. Vestibulum fermentum consectetur porttitor. Suspendisse imperdiet porttitor tortor, eget elementum tortor mollis non.</p>
</div>
</section>
window.addEventListener('load', getNaveBar, false)
// Get the offset position of the navbar
var getNaveBar = function(){
const allSections = document.querySelectorAll("allSections");
const allSectionsDoc = allSections.contentDocument;
const section = allSectionsDoc.getElementById("section1");
allSectionsDoc.scrollingElement.scrollTop = section.offsetTop;
section.innerText = "Y offset after scrolling: " +
allSections.contentWindow.pageYOffset + " pixels";
}
I am trying to shorted long string by number of characters (approximately) and finding sentence end (dot). Obviously this is not going to be 100% correct in all cases but its good enough. So for example, shorted string to 250 characters and find nearest dot as sentence end.
So having this:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed in neque. Vivamus tellus. Donec magna. Donec consequat hendrerit magna. In iaculis neque eget nisi. Maecenas vehicula, leo eu commodo aliquam, sem dolor iaculis eros, vel mollis sem urna ac sapien. Integer mattis dui ut erat. Phasellus nibh magna, tempor vitae, dictum sed, vehicula sed, mauris. In enim arcu, porta vel, dictum eu, pretium a, ipsum. Donec cursus, lorem ac posuere viverra, sem tellus accumsan dolor, vel accumsan tortor est et est.
Would create this:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed in neque. Vivamus tellus. Donec magna. Donec consequat hendrerit magna. In iaculis neque eget nisi. Maecenas vehicula, leo eu commodo aliquam, sem dolor iaculis eros, vel mollis sem urna ac sapien.
Things to consider I think:
If there is no dot in the string, shorten string by word boundary (so not to break a word) and add ellipsis (...) on the end which would be this function:
function truncateString( str, n, useWordBoundary ){
if (str.length <= n) { return str; }
var subString = str.substr(0, n-1);
return (useWordBoundary
? subString.substr(0, subString.lastIndexOf(' '))
: subString) + "...";
};
How could one incorporate dot finding into this function?
One approach you can make is splitting upp the string into chars in an array. Looping over the array from position 250 to position 0 and breaking when you find a dot. Take that index of the dot and splice the original array from the starting char, 0, to the dot which is the index value of that dot plus one as splice doesnt include the last value. Then turning that array into a string again.
let string = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed in neque. Vivamus tellus. Donec magna. Donec consequat hendrerit magna. In iaculis neque eget nisi. Maecenas vehicula, leo eu commodo aliquam, sem dolor iaculis eros, vel mollis sem urna ac sapien. Integer mattis dui ut erat. Phasellus nibh magna, tempor vitae, dictum sed, vehicula sed, mauris. In enim arcu, porta vel, dictum eu, pretium a, ipsum. Donec cursus, lorem ac posuere viverra, sem tellus accumsan dolor, vel accumsan tortor est et est.";
let arrarOfChar = string.split(""); //turns string into array
let position = -1; //-1 indicates that no dot has been found
for(let i = 250 ; i >= 0 ; i--) { //loop from 250 to 0
if(arrarOfChar[i] == ".") { //if that char is equal to "."
position = i; //set the position value to that
break; //break the for loop
}
}
if(position > 0) { //only if we found a dot
let newShortArrayOfChar = arrarOfChar.slice(0,position+1); //shorten the array from 0 to the dot index
let finalString = ""; //this is the final string
for(let i = 0; i < newShortArrayOfChar.length ; i++) {
finalString += newShortArrayOfChar[i]; //loop over every char and add it to the string
}
}
else {
// position should be -1
//handle if no dot exists
}
One option would be to use a regular expression: search for n or fewer characters, ending in a ., and if that match fails (there are no dots within the desired substring), search for n or fewer characters, followed by a word character and a word boundary:
const input = `Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed in neque. Vivamus tellus. Donec magna. Donec consequat hendrerit magna. In iaculis neque eget nisi. Maecenas vehicula, leo eu commodo aliquam, sem dolor iaculis eros, vel mollis sem urna ac sapien. Integer mattis dui ut erat. Phasellus nibh magna, tempor vitae, dictum sed, vehicula sed, mauris. In enim arcu, porta vel, dictum eu, pretium a, ipsum. Donec cursus, lorem ac posuere viverra, sem tellus accumsan dolor, vel accumsan tortor est et est.`;
function truncateString( str, n, useWordBoundary ){
const pattern = new RegExp(`^(?:.{1,${n}}\\.` + (
useWordBoundary
? `|.{1,${n - 1}}\\w\\b)`
: ')'
));
const match = str.match(pattern);
if (match) return match[0];
else return 'Match failed';
}
console.log(truncateString(input, 70));
// first sentence is more than 50 characters long, so this fails:
console.log(truncateString(input, 50));
// unless you enable word boundaries:
console.log(truncateString(input, 50, true));
The regex pattern looks like:
^(?:.{1,50}\.|.{1,49}\w\b)
Breaking that down:
^ - Start of string
(?: - Non-capturing group that alternates between:
.{1,50}\. - 50 or fewer characters, followed by a ., or:
.{1,49}\w\b) - 49 or fewer characters, followed by a word character and a word boundary
Here is a pretty straightforward example that trims the string to 250 characters then walks backward looking for the first . if it doesn't find one then the entire 250 characters are returned and if it does it trims it to that .
var maxLength = 250;
function test() {
var input = document.getElementById('test').value;
var trimmed = input.substr(0, maxLength);
var i = trimmed.length;
while (i > 0) {
if (trimmed[i] == '.') {
break;
}
i--;
}
var endResult = i > 1 ? trimmed.substr(0, i + 1) : trimmed;
endResult += endResult.length < input.length ? ' ...' : '';
document.getElementById('output').innerHTML = endResult;
}
.boxsizingBorder {
width: 100%;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
<button onclick="test()">
test
</button>
<textarea id="test" class="boxsizingBorder" rows="5">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed in neque. Vivamus tellus. Donec magna. Donec consequat hendrerit magna. In iaculis neque eget nisi. Maecenas vehicula, leo eu commodo aliquam, sem dolor iaculis eros, vel mollis sem urna ac sapien. Integer mattis dui ut erat. Phasellus nibh magna, tempor vitae, dictum sed, vehicula sed, mauris. In enim arcu, porta vel, dictum eu, pretium a, ipsum. Donec cursus, lorem ac posuere viverra, sem tellus accumsan dolor, vel accumsan tortor est et est.</textarea>
<p id="output"></p>
I would suggest to add two more parameters to your function in order to express what the extreme limits are for the offset at which the string would be clipped.
So for instance, if n is 250, you could provide 200 as a minimum and maybe 270 as the ultimate maximum for the cut-off point.
Then here is how I would include the dot-break possibility:
function truncateString( str, min, n, max, useWordBoundary ){
if (str.length <= max) return str;
if (useWordBoundary) {
// Prefer to break after a dot:
var i = str.indexOf(".", n)+1; // Look forward
if (i < min || i > max) i = str.slice(0, n).lastIndexOf(".")+1; // ...or backward
if (i >= min) return str.slice(0, i); // No ellipsis necessary
// If dot-break is impossible, try word break:
i = str.indexOf(" ", n); // Look forward
if (i < min || i > max) i = str.slice(0, n).lastIndexOf(" "); // ...backward
if (i >= min) n = i; // Found an acceptable position
}
return str.substr(0, n) + " ...";
}
// Example:
var str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed in neque. Vivamus tellus. Donec magna. Donec consequat hendrerit magna. In iaculis neque eget nisi. Maecenas vehicula, leo eu commodo aliquam, sem dolor iaculis eros, vel mollis sem urna ac sapien. Integer mattis dui ut erat. Phasellus nibh magna, tempor vitae, dictum sed, vehicula sed, mauris. In enim arcu, porta vel, dictum eu, pretium a, ipsum. Donec cursus, lorem ac posuere viverra, sem tellus accumsan dolor, vel accumsan tortor est et est.";
console.log(truncateString(str, 200, 250, 270, true));
console.log(truncateString(str, 200, 250, 255, true));
My code is supposed to place a banner after x amount of words. The code is working, but not as it should, as it is using slice to make the counting or slicing.
I need to use (count >= 20) instead of slice(0, 20)
This way the words in the text will be counted, instead counting the lines.
This is the code that does what I need: https://jsfiddle.net/714Lmgfu/3/
However, there is a loop in this code, which replicates the image (As show in the Fiddle) and I was not able to make return false working.
So I got some help and this was the final result https://jsfiddle.net/scadp0ar/, this code is working the way it should, except that, as stated before, it doesn't count the words. What should I change to make it count the words instead?
For example, change:
var img = '<img src="http://blog.leadlovers.com.br/wp-content/uploads/sites/23/2014/03/marca21-160x160.png" />'
$(".newsitem_text").html(function (i, h) {
return h.replace(h.split(/\s+/).slice(0, 20).join(' '), function (m) {
return m + img; });
});
for:
function check() {
if (count >= 20) {
newHtml += '<img src="http://blog.leadlovers.com.br/wp-content/uploads/sites/23/2014/03/marca21-160x160.png" />'
count = 0;
}
}
var img = '<img src="http://blog.leadlovers.com.br/wp-content/uploads/sites/23/2014/03/marca21-160x160.png" />'
$(".newsitem_text").html(function (i, h) {
// Match a word followed by one or more spaces 20 times
// Insert <img>-tag
// Repeat
return h.replace(/([^\s]+\s+){20}/g, function (m) {
return m + img;
});
});
Breakdown:
/ # Start regex
( # Start capturing group
[^\s]+ # Match everything - but space - 1 or more times
# could also be written as .+? that means:
# match everything 1 or more times, but not gready (meaning that if a space is encountered it will stop matching)
\s+ # Match space 1 or more times
) # End group
{20} # repeat 20 times
/ # End regex
g # global flag - will run the regex multiply times until no more matches are posible
Try using String.prototype.match() with RegExp /\w+./g to match alphanumeric character followed by any single character , Array.prototype.splice()
var img = '<img src="http://blog.leadlovers.com.br/wp-content/uploads/sites/23/2014/03/marca21-160x160.png" />'
var text = document.querySelector(".newsitem_text");
var html = text.innerHTML,
matches = html.match(/\w+./g);
matches.splice(20, 0, img);
text.innerHTML = matches.join(" ");
<div style="width:450px; margin-left:auto; margin-right:auto" class="newsitem_text">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec pellentesque urna eu pulvinar maximus. Sed elit nunc, vestibulum ut eros vitae, pellentesque rhoncus ipsum. In et metus non diam porttitor maximus iaculis nec lectus. Quisque sodales scelerisque
auctor. Nam rutrum venenatis eros, eu condimentum erat placerat ut. Pellentesque sed tempus sem, eu viverra ipsum. Vestibulum nec turpis convallis, dapibus massa vitae, posuere mauris. Suspendisse mattis tincidunt lorem. Aliquam erat volutpat. Nullam
at tincidunt erat, maximus laoreet ipsum. Quisque nunc neque, semper tincidunt placerat eget, blandit a ante. Suspendisse pulvinar, velit eu ultrices pulvinar, lacus sapien tincidunt ipsum, eget sollicitudin mauris eros molestie ex. Etiam quis orci
dui. Phasellus vestibulum mollis molestie. Nam condimentum ornare nisl, sed finibus risus tempus vel. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Interdum et malesuada fames ac ante ipsum primis in faucibus. Vestibulum eget ullamcorper
lorem. Aliquam mollis elit in sem dapibus dapibus. Proin vel massa a arcu dictum tincidunt in ut ante. Sed feugiat tempus dictum. Praesent in leo ullamcorper, sodales turpis et, vehicula tellus. Duis pellentesque dui ac turpis tristique imperdiet. Sed
sed orci lectus. Suspendisse non egestas sem, sed tincidunt sem. Etiam laoreet dui sem. Mauris hendrerit massa tempus, euismod arcu sit amet, eleifend quam. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Phasellus
id fringilla mauris. Cras dapibus non lacus at finibus. Nullam vitae sagittis neque. Mauris libero velit, interdum non vehicula non, lacinia non augue. Maecenas elementum lacinia interdum. Morbi eget mollis nisl. Integer accumsan condimentum tellus,
lacinia pellentesque urna volutpat a. Nullam semper sem et erat commodo sollicitudin. Proin rhoncus felis eu aliquam venenatis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nulla pretium velit eu molestie
condimentum. Vestibulum vitae velit mi. Integer nec leo quam. Nam pulvinar ligula congue consectetur tristique. Donec placerat faucibus diam sit amet fermentum. Ut id pellentesque risus. Nunc lacus orci, rhoncus ut risus sed, mattis posuere tellus.
Nulla pellentesque eros sed neque consectetur dictum.</div>
jsfiddle https://jsfiddle.net/scadp0ar/3/
You should try something like this:
var img = '<img src="http://blog.leadlovers.com.br/wp-content/uploads/sites/23/2014/03/marca21-160x160.png" />';
jQuery( document ).ready(function( $ ) {
$(".newsitem_text").html(getTextWithImageBetweenWords($(".newsitem_text").html(),20));
});
function getTextWithImageBetweenWords(text, count){
var split_text = text.split(' ');
var _out = [];
var words = split_text.length;
for(var i=0;i < words; i++){
if(i !== 0 && i === count){
_out[i] = split_text[i] + img;
}
else{
_out[i] = split_text[i];
}
}
return _out.join(' ');
}
This is a more readable and easy way to accomplish this, here is the JSFiddle!
Note: if you want to repeat the image every n (20 in your case) words, just change i === count for i % count === 0.
From your comment, you may want to edit the question (just for clarity not trying to be a jerk). Also, by splitting at space, the count is of words. '\s' is space '\n' is new line '\t' is carriage return, '\r\n' is a special type of carriage return. You could potentially make a more complicated regex to cover everything that is not a new line or a space '\t|\s|\r\n'. To place the image within lines, you can use a styling trick as explained later.
If you want to have the image not repeat change:
function check() {
if (count >= 20) {
newHtml += '<img src="http://blog.leadlovers.com.br/wp-content/uploads/sites/23/2014/03/marca21-160x160.png" />'
count = 0;
}
}
For an even nicer fit, try align="right" which will wrap the text around the image.
//jQuery(function ($) {
jQuery( document ).ready(function( $ ) {
var img = '<img align="right" src="http://blog.leadlovers.com.br/wp-content/uploads/sites/23/2014/03/marca21-160x160.png" />'
$(".newsitem_text").html(function (i, h) {
return h.replace(h.split(/\s+/).slice(20,21).join(' '), function (m) {
return m + img; });
});
});
to
function check() {
if (count == 20) {
newHtml += '<img src="http://blog.leadlovers.com.br/wp-content/uploads/sites/23/2014/03/marca21-160x160.png" />';
}
}
To avoid using a nasty loop, you could slice at a different location or use splice:
//jQuery(function ($) {
jQuery( document ).ready(function( $ ) {
var img = '<img src="http://blog.leadlovers.com.br/wp-content/uploads/sites/23/2014/03/marca21-160x160.png" />'
$(".newsitem_text").html(function (i, h) {
return h.replace(h.split(/\s+/).slice(20, 21).join(' '), function (m) {
return m + img; });
});
});
To wrap your image within the words use align="left" or align="right" in the image tag.
<img align="right" src="http://blog.leadlovers.com.br/wp-content/uploads/sites/23/2014/03/marca21-160x160.png" />
The purpose of this script is to show a "live preview" of how text will be formatted once the user selects a checkbox. It is being used in a Wordpress plugin.
If user selects the "bold" checkbox, the Lorem Ipsum "div" text should appear with opening and closing "strong" tags.
This has worked sporadically, such as when I write the script only to address one or the other, i.e., "strong" or "em", but I want to be able to have the paragraph (the parText object) always reflect all the choices.
I imagine something is wrong with my function definition and callback. JQuery is less familiar to me than PHP. Here is the code I am working with:
$(document).ready(function(){
parText = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce ornare tempus magna, eu tempor nisi posuere at. In sagittis nulla quis metus convallis ornare sit amet id ligula. Duis posuere scelerisque justo, in consequat nulla euismod et. Donec consequat nec magna vel aliquet. Suspendisse felis leo, aliquet at egestas non, placerat non erat. Pellentesque placerat quam nec erat fringilla, ut accumsan lorem pharetra. In volutpat nunc at ligula elementum lacinia. Donec sit amet lectus lobortis enim tempus semper at ut lacus.';
//SET THE VALUE OF THE HTML TAGS
boldOpen = '<strong>';
boldClosed = '</strong>';
italicsOpen = '<em>';
italicsClosed = '</em>';
//FUNCTION TO RETURN HTML VALUE
function htmlOpenCloseTags() {
//bold and italics
if ( $('#select_bold').prop('checked') == true && $('#select_italics').prop('checked') == true ) {
htmlOpen = boldOpen + italicsOpen;
htmlClose = boldClosed + italicsClosed;
}
//bold only
else if ( $('#select_bold').prop('checked') == true && $('#select_italics').prop('checked') == false ) {
htmlOpen = boldOpen;
htmlClose = boldClosed;
}
//italics only
else if ( $('#select_bold').prop('checked') == false && $('#select_italics').prop('checked') == true ) {
htmlOpen = italicsOpen;
htmlClose = italicsClosed;
}
//neither
else {
htmlOpen = '';
htmlClose = '';
}
var output = htmlOpen + parText + htmlClose;
return output;
}
//BOLD LIVE PREVIEW
$('#select_bold').change(function(){
$('#live_preview').hide();
htmloutput = htmlOpenCloseTags();
$('#live_preview').html(htmloutput);
$('#live_preview').fadeIn('fast');
});
//ITALICS LIVE PREVIEW
$('#select_italics').change(function(){
$('#live_preview').hide();
$('#live_preview').html(htmlOpen + parText + htmlClose);
$('#live_preview').fadeIn('fast');
});
//end jquery
});
Here's a working example http://jsfiddle.net/W8774/1/.
$(document).ready(function(){
var parText = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce ornare tempus magna, eu tempor nisi posuere at. In sagittis nulla quis metus convallis ornare sit amet id ligula. Duis posuere scelerisque justo, in consequat nulla euismod et. Donec consequat nec magna vel aliquet. Suspendisse felis leo, aliquet at egestas non, placerat non erat. Pellentesque placerat quam nec erat fringilla, ut accumsan lorem pharetra. In volutpat nunc at ligula elementum lacinia. Donec sit amet lectus lobortis enim tempus semper at ut lacus.';
//FUNCTION TO RETURN HTML VALUE
function htmlOpenCloseTags() {
var htmlOpen = '';
var htmlClose = '';
if ($('#select_bold').prop('checked')) {
htmlOpen = '<strong>' + htmlOpen;
htmlClose += '</strong>';
}
if ($('#select_italics').prop('checked')) {
htmlOpen = '<em>' + htmlOpen;
htmlClose += '</em>';
}
return htmlOpen + parText + htmlClose;
}
//BOLD LIVE PREVIEW
$('#select_bold').change(function(){
$('#live_preview').hide();
var htmloutput = htmlOpenCloseTags();
$('#live_preview').html(htmloutput);
$('#live_preview').fadeIn('fast');
});
//ITALICS LIVE PREVIEW
$('#select_italics').change(function(){
$('#live_preview').hide();
var htmloutput = htmlOpenCloseTags();
$('#live_preview').html(htmloutput);
$('#live_preview').fadeIn('fast');
});
});
hello im doing something like how to replace dots inside quote in sentence with regex
var string = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. "Vestibulum interdum dolor nec sapien blandit a suscipit arcu fermentum. Nullam lacinia ipsum vitae enim consequat iaculis quis in augue. Phasellus fermentum congue blandit. Donec laoreet, ipsum et vestibulum vulputate, risus augue commodo nisi, vel hendrerit sem justo sed mauris." Phasellus ut nunc neque, id varius nunc. In enim lectus, blandit et dictum at, molestie in nunc. Vivamus eu ligula sed augue pretium tincidunt sit amet ac nisl. "Morbi eu elit diam, sed tristique nunc."';
// seperate the quotes
var quotes = string.match(/"(.)+?"/g);
var test = [];
// for each quotes
for (var i = quotes.length - 1; i >= 0; i--) {
// replace all the dot inside the quote
test[i] = quotes[i].replace(/\./g, '[dot]');
};
console.log(test);
lets say we already make the change with the regex, but im stuck at how can we join it back to the existing var string as my result is seperated in var test ? or theres a better way?
the output should be something like
Lorem ipsum dolor sit amet, consectetur adipiscing elit. "Vestibulum interdum dolor nec sapien blandit a suscipit arcu fermentum[dot]Nullam lacinia ipsum vitae enim consequat iaculis quis in augue[dot] Phasellus fermentum congue blandit[dot] Donec laoreet, ipsum et vestibulum vulputate, risus augue commodo nisi, vel hendrerit sem justo sed mauris[dot]" Phasellus ut nunc neque, id varius nunc. In enim lectus, blandit et dictum at, molestie in nunc. Vivamus eu ligula sed augue pretium tincidunt sit amet ac nisl. "Morbi eu elit diam, sed tristique nunc[dot]"
*ps im not sure the title is corrent
thanks
You could instead just split at ", do the replacement in every second array element, then join again:
var parts = string.split('"');
for (var i = 1; i < parts.length; i += 2) {
parts[i] = parts [i].replace(/\./g, '[dot]');
};
string = parts.join('"');
Since split will create an empty string at index 0 if the string starts with " this should work in all cases.
Note that the edge case of a trailing unmatched " will lead to every dot after that " to be replaced as well. If you do not want this, simply change the for condition to i < parts.length - 1.
JSFiddle Demo
Use regexp but with replace function:
string.replace(/"[^"]+"/g, function(m) {return m.replace(/\./g,"[dot]")})