Convert multi-line wrapped paragraphs into single line paragraphs - javascript

Let's say we have this text inside a single <p> that uses the entire screen space:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed vestibulum
sem consectetur, tempor massa quis, bibendum mauris. Curabitur et leo
pharetra, condimentum mi vel, gravida mi. Integer pulvinar nibh in
laoreet auctor. Donec in tortor in augue maximus fermentum et non erat.
Sed auctor feugiat dolor eget efficitur. Vivamus nec urna lorem. Duis
lobortis semper tempor. Vestibulum dolor lectus, consectetur.
If we were using a smaller display, it would look like something this:
Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Sed vestibulum sem
consectetur, tempor massa quis, bibendum
mauris. Curabitur et leo pharetra,
condimentum mi vel, gravida mi. Integer
pulvinar nibh in laoreet auctor. Donec
in tortor in augue maximus fermentum et
non erat. Sed auctor feugiat dolor eget
efficitur. Vivamus nec urna lorem. Duis
lobortis semper tempor. Vestibulum dolor
lectus, consectetur.
The paragraph has now more lines than before. With that said, I want to convert this single paragraph into one <p> per line to apply different styling to each one of them, but also taking into acount that the number of lines can change from the viewport/browser window size. This is so that the text styling can be responsive.
HTML:
<p>Lorem ipsum dolor sit amet, consectetur</p>
<p>adipiscing elit. Sed vestibulum sem</p>
<p>consectetur, tempor massa quis, bibendum</p>
<p>mauris. Curabitur et leo pharetra,</p>
<p>condimentum mi vel, gravida mi. Integer</p>
<p>pulvinar nibh in laoreet auctor. Donec</p>
<p>in tortor in augue maximus fermentum et</p>
<p>non erat. Sed auctor feugiat dolor eget</p>
<p>efficitur. Vivamus nec urna lorem. Duis</p>
<p>lobortis semper tempor. Vestibulum dolor</p>
<p>lectus, consectetur.</p>
I'm looking for a pure JavaScript (aka no jQuery) solution.

document.body.addEventListener("load", function(){
var defaultCharacterWidth = 8; //8 px
var textboxWidth = document.querySelector(".orgText").offsetWidth;
var breakIndex = Math.floor(textboxWidth/defaultCharacterWidth);
var i = 0;
var savedIndex = 0;
var whitespace = 0;
document.querySelector(".orgText").textContent.match(/[\s\S]/g).forEach(function(element, index){
if (element.match(/\s/))
{
whitespace = index;
}
if (i == breakIndex)
{
i = -1;
//get nearest whitespace
document.querySelector(".textcontainer").innerHTML += "<p>" + document.querySelector(".orgText").value.slice(savedIndex, whitespace) + "</p>";
savedIndex = whitespace; //save the last whitespace
}
i++;
});
}, true);
<textarea class="orgText" style="overflow:hidden;width:100%">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed vestibulum sem consectetur, tempor massa quis, bibendum mauris. Curabitur et leo pharetra, condimentum mi vel, gravida mi. Integer pulvinar nibh in laoreet auctor. Donec in tortor in augue maximus fermentum et non erat. Sed auctor feugiat dolor eget efficitur. Vivamus nec urna lorem. Duis lobortis semper tempor. Vestibulum dolor lectus, consectetur.
</textarea>
<div class="textcontainer">
</div>
This is a little testcode. It uses the fact that a textarea has a fixed character width. But that's not the case for most fonts. The above code iterates over every character and checks if it's exceeds the width of the container based upon the detection of a whitespace character.
You can also use the code below to calculate the width of a string.
function getPixelLengthOfString()
{
var tempNode = document.createElement("span");
tempNode.innerHTML = this;
document.body.appendChild(tempNode);
var stringPixelLength = tempNode.offsetWidth;
document.body.removeChild(tempNode);
return stringPixelLength;
}
These pieces of code should point you in a direction of the correct answer.

Related

RegEx for matching text between two tags [duplicate]

This question already has answers here:
Regular expression to get a string between two strings in Javascript
(13 answers)
Closed 3 years ago.
I have this text
Donec ante sapien, gravida id risus eget,
<exclude>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec quis neque ex. Aenean ac leo quis ex lobortis aliquam. Donec libero dolor, sodales in molestie vel, sagittis at nulla. Proin egestas dolor turpis. Aliquam erat volutpat. Nunc eget enim varius, condimentum tortor sit amet, aliquet magna. Phasellus ut libero quis diam dignissim interdum. Sed commodo iaculis vestibulum. Quisque viverra diam sed orci rhoncus luctus. Mauris leo mauris, consequat at lacinia sit amet, viverra vitae enim. Donec maximus, ipsum in bibendum volutpat, est erat dapibus leo, et iaculis arcu augue in dolor.
<exclude>
Donec ante sapien, gravida id risus eget,
I want to get the text between <exclude> tags, I have this express but it does not work for me : /\<exclude\>/g
Note:
The tag could anything even something like #x it is just a delimiter to the that portion of the text.
How do I solve this problem?
Something like this should do the job:
<exclude>((?:[^<]|<(?!exclude>))*)(?=<exclude>)
^---1---^|^----------2----------^|^-----3-----^
+-----------4-----------+
This specifies the following:
Match the characters <exclude>.
Accept all characters that are not < or < not followed by exclude>.
The match may only end if it is followed by the characters <exclude>.
Capture the characters between the two tags in group 1.
For something simpler like the tag #x you can use the same principal:
#x((?:[^#]|#(?!x))*)(?=#x)
var text = `
Donec ante sapien, gravida id risus eget,
<exclude>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec quis neque ex. Aenean ac leo quis ex lobortis aliquam. Donec libero dolor, sodales in molestie vel, sagittis at nulla. Proin egestas dolor turpis. Aliquam erat volutpat. Nunc eget enim varius, condimentum tortor sit amet, aliquet magna. Phasellus ut libero quis diam dignissim interdum. Sed commodo iaculis vestibulum. Quisque viverra diam sed orci rhoncus luctus. Mauris leo mauris, consequat at lacinia sit amet, viverra vitae enim. Donec maximus, ipsum in bibendum volutpat, est erat dapibus leo, et iaculis arcu augue in dolor.
<exclude>
Donec ante sapien, gravida id risus eget,
`.trim();
var regex = /<exclude>((?:[^<]|<(?!exclude>))*)(?=<exclude>)/g;
while (match = regex.exec(text)) {
console.log(match[1]);
}
Assuming your data is correct and this isn't actually XML (for which you should use an XML parser instead). Given you specific example, this would work:
var str = `Donec ante sapien, gravida id risus eget,
<exclude>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec quis neque ex. Aenean ac leo quis ex lobortis aliquam. Donec libero dolor, sodales in molestie vel, sagittis at nulla. Proin egestas dolor turpis. Aliquam erat volutpat. Nunc eget enim varius, condimentum tortor sit amet, aliquet magna. Phasellus ut libero quis diam dignissim interdum. Sed commodo iaculis vestibulum. Quisque viverra diam sed orci rhoncus luctus. Mauris leo mauris, consequat at lacinia sit amet, viverra vitae enim. Donec maximus, ipsum in bibendum volutpat, est erat dapibus leo, et iaculis arcu augue in dolor.
<exclude>
Donec ante sapien, gravida id risus eget,`;
console.log(/<exclude>(.*?)<exclude>/gs.exec(str)[1]);
Your are going to look for something that matches <exclude> then we are going to group everything up to the next <exclude>. Although it makes no difference to this example, we use a lazy quantifier so if there are multiple pairs of <exclude> tags, you only match up to the next <exclude> and not the last <exclude>.
var str =
"Donec ante sapien, gravida id risus eget,\n" +
"<exclude>\n" +
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec quis neque ex. Aenean ac leo quis ex lobortis aliquam. Donec libero dolor, sodales in molestie vel, sagittis at nulla. Proin egestas dolor turpis. Aliquam erat volutpat. Nunc eget enim varius, condimentum tortor sit amet, aliquet magna. Phasellus ut libero quis diam dignissim interdum. Sed commodo iaculis vestibulum. Quisque viverra diam sed orci rhoncus luctus. Mauris leo mauris, consequat at lacinia sit amet, viverra vitae enim. Donec maximus, ipsum in bibendum volutpat, est erat dapibus leo, et iaculis arcu augue in dolor.\n" +
"<exclude>\n" +
"Donec ante sapien, gravida id risus eget,\n"
var regex = /<exclude>([\S\s]*?)<exclude>/g;
var found = regex.exec( str )[1];
console.log( found );
One way to design an expression for such output is to use capturing groups that most of answers are already using that.
Also, you can add other flags such as multiline or single line (depending on your input string) to your expression, as you wish. This tool might help you to do so, design and test your expressions and see how they work:
RegEx
(.*)(<exclude>)(.+)(<exclude>)(.*)
Graph
This graph shows how the expression would work:
Performance
This JavaScript snippet shows the performance of this expression using a simple 1-million times for loop.
repeat = 1000000;
start = Date.now();
for (var i = repeat; i >= 0; i--) {
var string = "Donec ante sapien, gravida id risus eget,\n" +
"<exclude>\n" +
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec quis neque ex. Aenean ac leo quis ex lobortis aliquam. Donec libero dolor, sodales in molestie vel, sagittis at nulla. Proin egestas dolor turpis. Aliquam erat volutpat. Nunc eget enim varius, condimentum tortor sit amet, aliquet magna. Phasellus ut libero quis diam dignissim interdum. Sed commodo iaculis vestibulum. Quisque viverra diam sed orci rhoncus luctus. Mauris leo mauris, consequat at lacinia sit amet, viverra vitae enim. Donec maximus, ipsum in bibendum volutpat, est erat dapibus leo, et iaculis arcu augue in dolor.\n" +
"<exclude>\n" +
"Donec ante sapien, gravida id risus eget,\n";
var regex = /(.+)(<exclude>)(.+)(<exclude>)(.+)/gms;
var match = string.replace(regex, "$3");
}
end = Date.now() - start;
console.log("YAAAY! \"" + match + "\" is a match 💚💚💚 ");
console.log(end / 1000 + " is the runtime of " + repeat + " times benchmark test. 😳 ");

Text Highlight using Xpath

I am highlighting selected text by using the following xpath and offsets.
Here is an example selection of text I am using to debug.
[{
commonAncestorContainer: "/xhtml:html[0001]/xhtml:body[0001]/xhtml:p[0002]",
startContainer: "/xhtml:html[0001]/xhtml:body[0001]/xhtml:p[0002]",
startOffset:0,
endContainer: "/xhtml:html[0001]/xhtml:body[0001]/xhtml:p[0002]",
endOffset:1,
color: "purple"
}]
This selection above works nicely and highlights the selected paragraph.
Now here is the part I am stuck on, as soon as I add text to the paragraph it fails to highlight the text.
Here is the example with selected paragraph and text, so in theory this should only select the text inside the paragraph that you selected. Changes are marked in bold
[{
commonAncestorContainer: "/xhtml:html[0001]/xhtml:body[0001]/xhtml:p[0002]/text()[0]",
startContainer: "/xhtml:html[0001]/xhtml:body[0001]/xhtml:p[0002]/text()[0]",
startOffset:288,
endContainer: "/xhtml:html[0001]/xhtml:body[0001]/xhtml:p[0002]/text()[0]",
endOffset:330,
color: "purple"
}]
test.html (this uses highlight.show)
function highlightTest() {
$MON.highlight.show([
{
commonAncestorContainer: "/xhtml:html[0001]/xhtml:body[0001]/xhtml:p[0001]",
startContainer: "/xhtml:html[0001]/xhtml:body[0001]/xhtml:p[0001]",
startOffset:0,
endContainer: "/xhtml:html[0001]/xhtml:body[0001]/xhtml:p[0001]",
endOffset:1,
color: "yellow"
},
{
commonAncestorContainer: "/xhtml:html[0001]/xhtml:body[0001]/xhtml:p[0002]/text()[0]",
startContainer: "/xhtml:html[0001]/xhtml:body[0001]/xhtml:p[0002]/text()[0]",
startOffset:288,
endContainer: "/xhtml:html[0001]/xhtml:body[0001]/xhtml:p[0002]/text()[0]",
endOffset:330,
color: "purple"
}
]);
highlight.js(this uses xpath.element)
show: function(selections)
{
for (var i in selections)
{
var selection = selections[i];
var ancestor = $MON.xpath.element(selection["commonAncestorContainer"]);
ancestor.contentEditable = "true";
var col = selection["color"] ? selection["color"] : "yellow";
var range = document.createRange();
var startElement = $MON.xpath.element(selection["startContainer"]);
var startOffset = selection["startOffset"];
var endElement = $MON.xpath.element(selection["endContainer"]);
var endOffset = selection["endOffset"];
range.setStart(startElement, startOffset);
range.setEnd(endElement, endOffset);
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
document.execCommand("HiliteColor", false, col);
window.getSelection().removeAllRanges();
ancestor.contentEditable = "false";
}
}
xpath.js
(this returns the corresponding element given the xpath, back to highlight.js)
element: function (expr) {
var resolver = function (prefix) {
if ("xhtml" == prefix) {
return "http://www.w3.org/1999/xhtml";
}
}
var result = document.evaluate(expr, document, resolver, 9, null).singleNodeValue;
return result;
}
HTML
<body>
<p>
1 Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse tellus ligula, ullamcorper vitae elementum sed, rhoncus a ligula. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras et pulvinar augue. Proin non semper mi. Nullam justo velit, vehicula eu congue vitae, tincidunt sit amet urna. Aliquam blandit rutrum dignissim. Donec dapibus nisl arcu, eu eleifend tellus lobortis quis. Praesent quis hendrerit diam. Quisque ultricies lorem et turpis aliquam ornare. Phasellus dolor purus, lacinia eget porta vel, iaculis ac nisl. Phasellus vestibulum faucibus erat sit amet interdum.
</p>
<p>
2 Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse tellus ligula, ullamcorper vitae elementum sed, rhoncus a ligula. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras et pulvinar augue. Proin non semper mi. Nullam justo velit, vehicula eu congue vitae, tincidunt sit amet urna. Aliquam blandit rutrum dignissim. Donec dapibus nisl arcu, eu eleifend tellus lobortis quis. Praesent quis hendrerit diam. Quisque ultricies lorem et turpis aliquam ornare. Phasellus dolor purus, lacinia eget porta vel, iaculis ac nisl. Phasellus vestibulum faucibus erat sit amet interdum.
</p>
<p>
3 Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse tellus ligula, ullamcorper vitae elementum sed, rhoncus a ligula. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras et pulvinar augue. Proin non semper mi. Nullam justo velit, vehicula eu congue vitae, tincidunt sit amet urna. Aliquam blandit rutrum dignissim. Donec dapibus nisl arcu, eu eleifend tellus lobortis quis. Praesent quis hendrerit diam. Quisque ultricies lorem et turpis aliquam ornare. Phasellus dolor purus, lacinia eget porta vel, iaculis ac nisl. Phasellus vestibulum faucibus erat sit amet interdum.
</p>
<p>
4 Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse tellus ligula, ullamcorper vitae elementum sed, rhoncus a ligula. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras et pulvinar augue. Proin non semper mi. Nullam justo velit, vehicula eu congue vitae, tincidunt sit amet urna. Aliquam blandit rutrum dignissim. Donec dapibus nisl arcu, eu eleifend tellus lobortis quis. Praesent quis hendrerit diam. Quisque ultricies lorem et turpis aliquam ornare. Phasellus dolor purus, lacinia eget porta vel, iaculis ac nisl. Phasellus vestibulum faucibus erat sit amet interdum.
</p>
<p>
5 Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse tellus ligula, ullamcorper vitae elementum sed, rhoncus a ligula. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras et pulvinar augue. Proin non semper mi. Nullam justo velit, vehicula eu congue vitae, tincidunt sit amet urna. Aliquam blandit rutrum dignissim. Donec dapibus nisl arcu, eu eleifend tellus lobortis quis. Praesent quis hendrerit diam. Quisque ultricies lorem et turpis aliquam ornare. Phasellus dolor purus, lacinia eget porta vel, iaculis ac nisl. Phasellus vestibulum faucibus erat sit amet interdum.
</p>
<p>
6 Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse tellus ligula, ullamcorper vitae elementum sed, rhoncus a ligula. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras et pulvinar augue. Proin non semper mi. Nullam justo velit, vehicula eu congue vitae, tincidunt sit amet urna. Aliquam blandit rutrum dignissim. Donec dapibus nisl arcu, eu eleifend tellus lobortis quis. Praesent quis hendrerit diam. Quisque ultricies lorem et turpis aliquam ornare. Phasellus dolor purus, lacinia eget porta vel, iaculis ac nisl. Phasellus vestibulum faucibus erat sit amet interdum.
</p>
</body>
Log on text selection, gets the selected xpath
38:Selected text: Lorem
44:Collapsed: false
45:Ancestor container: /xhtml:html[0001]/xhtml:body[0001]/xhtml:p[0002]/text()[0001]
46:Start container: /xhtml:html[0001]/xhtml:body[0001]/xhtml:p[0002]/text()[0001]
47:Start offset: 7
48:End container: /xhtml:html[0001]/xhtml:body[0001]/xhtml:p[0002]/text()[0001]
49:End offset: 12
Update (my problem was)
I had to add
document.designMode = "on";
before i set the hilite color
here is a link to js fiddle
http://jsfiddle.net/E2BbX/11/
XPath indexes are one-based. Try
startContainer: "/xhtml:html[0001]/xhtml:body[0001]/xhtml:p[0002]/text()[1]
and so on.

How to create tooltip over text selection without wrapping?

My end goal is to create a tooltip over a text selection. The user will then be able to interact with the tooltip similar to . Please note that I was able to accomplish this by wrapping selected text in a tag and then creating the tooltip on it however this is no longer an option for me due to some other requirements and functionality issues. If you notice in the image above in element inspector, the selected text is not wrapped in any kind of tag, the tooltip is just created over the selection. I have already looked at this and it will not work for me because mouse position may not be the same as the end of selection. I need the actual selection position.
General question: What is the best way to accomplish this?
More specific questions:
Should I be using the coordinates of the selection? If so is there a way to get the coordinates of the top corners of the rectangular selection so I can find the mid point and create a the tooltip over that.
Is there a way to get that selection as an element? So I can just place a tooltip over that? (Note the selection can be multiple nodes)
Assuming something selected
var selection = window.getSelection(), // get the selection then
range = selection.getRangeAt(0), // the range at first selection group
rect = range.getBoundingClientRect(); // and convert this to useful data
rect is now a Object which holds the positions relative the the current scroll coordinates of the Window. More info on this here. If you want to be even more precise, you can use getClientRects which returns a list of such Objects, which you would then have to put together to form the area of the selection.
Now, to draw a box around it (I'll take the easy route using fixed for demonstration purposes)
var div = document.createElement('div'); // make box
div.style.border = '2px solid black'; // with outline
div.style.position = 'fixed'; // fixed positioning = easy mode
div.style.top = rect.top + 'px'; // set coordinates
div.style.left = rect.left + 'px';
div.style.height = rect.height + 'px'; // and size
div.style.width = rect.width + 'px';
document.body.appendChild(div); // finally append
You will probably want to take into consideration the scroll position so you can use absolute positioning. If there are no other scrollable elements, this means you just need to factor in the values of window.scrollX and window.scrollY, which are the position of the window's x and y coordinates in pixels at the time they're accessed.
var div = null;
function drawBorderAroundSelection() {
var selection = window.getSelection(), // get the selection then
range = selection.getRangeAt(0), // the range at first selection group
rect = range.getBoundingClientRect(); // and convert this to useful data
if (rect.width > 0) {
if (div) {
div.parentNode.removeChild(div);
}
div = document.createElement('div'); // make box
div.class = 'rect';
div.style.border = '2px solid black'; // with outline
div.style.position = 'fixed'; // fixed positioning = easy mode
div.style.top = rect.top + 'px'; // set coordinates
div.style.left = rect.left + 'px';
div.style.height = rect.height + 'px'; // and size
div.style.width = rect.width + 'px';
document.body.appendChild(div); // finally append
}
}
window.onmouseup = drawBorderAroundSelection;
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ut dolor porta neque vulputate auctor et a ligula. Quisque bibendum risus magna, eget feugiat erat faucibus sed. Phasellus sed massa elementum, laoreet ipsum non, dignissim orci. Aenean lobortis
nunc et purus molestie, vel consectetur ligula dapibus. In ut lorem mattis, commodo nisi aliquam, porta ante. Curabitur sit amet libero sed justo finibus porttitor. Donec ac est ultrices, pretium diam sed, blandit nunc. Morbi consequat finibus augue
vel ultricies. Vestibulum efficitur ante vitae cursus accumsan. Vestibulum rutrum ex ex, a egestas nisi malesuada eu. Pellentesque fermentum, ante id convallis luctus, tellus lectus viverra diam, sit amet convallis ligula lorem sit amet neque.
</p>
$(document).ready(function () {
function tweetButtonClick() {
let selectedText = document.getSelection().toString();
/*window.open(
"https://twitter.com/intent/tweet?url=https://www.linkedin.com/in/harsha-vardhan-ch-245197bb/&text=" +
selectedText
);*/
console.log("This is your selected text: ",selectedText);
}
const textSelectionTooltipContainer = document.createElement("div");
textSelectionTooltipContainer.setAttribute(
"id",
"textSelectionTooltipContainer"
);
textSelectionTooltipContainer.innerHTML = `<button id="textShareTwitterBtn">TWEET</button>`;
const bodyElement = document.getElementsByTagName("BODY")[0];
$("body").on("click", "#textShareTwitterBtn", tweetButtonClick);
bodyElement.addEventListener("mouseup", function (e) {
var textu = document.getSelection().toString();
if (!textu.length) {
textSelectionTooltipContainer.remove();
}
});
document
.getElementById("textToSelect")
.addEventListener("mouseup", function (e) {
let textu = document.getSelection().toString();
let matchu = /\r|\n/.exec(textu);
if (textu.length && !matchu) {
let range = document.getSelection().getRangeAt(0);
rect = range.getBoundingClientRect();
scrollPosition = $(window).scrollTop();
containerTop = scrollPosition + rect.top - 50 + "px";
containerLeft = rect.left + rect.width / 2 - 50 + "px";
textSelectionTooltipContainer.style.transform =
"translate3d(" + containerLeft + "," + containerTop + "," + "0px)";
bodyElement.appendChild(textSelectionTooltipContainer);
}
});
});
#textSelectionTooltipContainer {
will-change: transform;
position: absolute;
width: 100px;
height: 40px;
background: #f7d39d;
top: 0px;
left: 0px;
display: flex;
padding: 5px 10px;
box-sizing: border-box;
justify-content: center;
}
#textSelectionTooltipContainer button {
font-size: 14px;
border: 1px solid black;
background: none;
cursor: pointer;
margin: 0 2px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel='stylesheet' href='shareText.css' />
<title>Text Share Feature</title>
<script>
</script>
</head>
<body>
<div id="textToSelect">
<h1>HTML Ipsum Presents</h1>
<p><strong>Pellentesque habitant morbi tristique</strong> senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. <em>Aenean ultricies mi vitae est.</em> Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, <code>commodo vitae</code>, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci,
sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis.</p>
<h2>Header Level 2</h2>
<ol>
<li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>
<li>Aliquam tincidunt mauris eu risus.</li>
</ol>
<blockquote>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus magna. Cras in mi at felis aliquet congue. Ut a est eget ligula molestie gravida. Curabitur massa. Donec eleifend, libero at sagittis mollis, tellus est malesuada tellus, at luctus turpis
elit sit amet quam. Vivamus pretium ornare est.</p>
<p>
Curabitur massa. Donec eleifend, libero at sagittis mollis, tellus est malesuada tellus, at luctus turpis
</p>
</blockquote>
<h3>Header Level 3</h3>
<ul>
<li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>
<li>Aliquam tincidunt mauris eu risus.</li>
</ul>
<h1>HTML Ipsum Presents</h1>
<p><strong>Pellentesque habitant morbi tristique</strong> senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. <em>Aenean ultricies mi vitae est.</em> Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, <code>commodo vitae</code>, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci,
sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis.</p>
<h2>Header Level 2</h2>
<ol>
<li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>
<li>Aliquam tincidunt mauris eu risus.</li>
</ol>
<blockquote>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus magna. Cras in mi at felis aliquet congue. Ut a est eget ligula molestie gravida. Curabitur massa. Donec eleifend, libero at sagittis mollis, tellus est malesuada tellus, at luctus turpis
elit sit amet quam. Vivamus pretium ornare est.</p>
<p>
Curabitur massa. Donec eleifend, libero at sagittis mollis, tellus est malesuada tellus, at luctus turpis
</p>
</blockquote>
<h3>Header Level 3</h3>
<ul>
<li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>
<li>Aliquam tincidunt mauris eu risus.</li>
</ul>
<h1>HTML Ipsum Presents</h1>
<p><strong>Pellentesque habitant morbi tristique</strong> senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. <em>Aenean ultricies mi vitae est.</em> Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, <code>commodo vitae</code>, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci,
sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis.</p>
<h2>Header Level 2</h2>
<ol>
<li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>
<li>Aliquam tincidunt mauris eu risus.</li>
</ol>
<blockquote>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus magna. Cras in mi at felis aliquet congue. Ut a est eget ligula molestie gravida. Curabitur massa. Donec eleifend, libero at sagittis mollis, tellus est malesuada tellus, at luctus turpis
elit sit amet quam. Vivamus pretium ornare est.</p>
<p>
Curabitur massa. Donec eleifend, libero at sagittis mollis, tellus est malesuada tellus, at luctus turpis
</p>
</blockquote>
<h3>Header Level 3</h3>
<ul>
<li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>
<li>Aliquam tincidunt mauris eu risus.</li>
</ul>
<h1>HTML Ipsum Presents</h1>
<p><strong>Pellentesque habitant morbi tristique</strong> senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. <em>Aenean ultricies mi vitae est.</em> Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, <code>commodo vitae</code>, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci,
sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis.</p>
<h2>Header Level 2</h2>
<ol>
<li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>
<li>Aliquam tincidunt mauris eu risus.</li>
</ol>
<blockquote>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus magna. Cras in mi at felis aliquet congue. Ut a est eget ligula molestie gravida. Curabitur massa. Donec eleifend, libero at sagittis mollis, tellus est malesuada tellus, at luctus turpis
elit sit amet quam. Vivamus pretium ornare est.</p>
<p>
Curabitur massa. Donec eleifend, libero at sagittis mollis, tellus est malesuada tellus, at luctus turpis
</p>
</blockquote>
<h3>Header Level 3</h3>
<ul>
<li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>
<li>Aliquam tincidunt mauris eu risus.</li>
</ul>
</div>
<script src="shareText.js"></script>
</body>
</html>
window.open lets you open the twitter page(https://twitter.com/intent/tweet) where you can share the selected text and also url.

Getting an exact reference for a selected text in HTML

Let's assume that I have the following text within a single <p>... </p>
When a user selects a couple of words within the text, lets assume the first Quisque vestibulum is selected, I get the selected text with window.getSelection().toString(); then I apply some CSS tricks, lets say I underline the text.
When the user comes back one month later, I would like to underline same text again. How can I get an exact reference for the selected text for future reference? I don't want to highlight the second Quisque vestibulum.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum at
dolor sit amet augue tempor venenatis vitae et nibh. Donec dignissim
fringilla fermentum. In facilisis consectetur risus. Nam vel mauris
magna, a feugiat nisl. Quisque vestibulum, neque eu tristique
tristique, tortor mauris ornare magna, at ultricies augue orci sed
enim. Nulla magna ligula, dapibus vel commodo ac, sodales ut sem. Duis
lorem massa, consectetur sed molestie eget, posuere eu magna.
Pellentesque sollicitudin mattis facilisis. Nunc pulvinar metus et
diam dignissim sit amet pellentesque metus pretium. Quisque vestibulum, maecenas vel leo
sit amet diam iaculis sollicitudin.
You could use the search() or indexOf() and store the position of the string as well as the actual selected text.

join result that is separated by a diffrent regex match

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]")})

Categories