How to add prefix for each new line in JavaScript? - javascript

I am working on a react project. I have a string that may contain newlines in it. How do I inject a symbol at the start o each line? What would be the most efficient way? (I am thinking of exploding the string into an array and adding a chat at the start of each line but that seems like a really inefficient way of doing things)
Change this
var text = "Lorem ipsum dolor sit amet,
consectetur adipiscing elit.
Vestibulum pellentesque";
into
var text = "> Lorem ipsum dolor sit amet,
> consectetur adipiscing elit.
> Vestibulum pellentesque"
How to add a symbol after each instance of "\n"?

Maybe you can use tagged template literals (ES6)...
Verbose version with for...of
function addPrefix(str) {
let tmp = str[0].split('\n'),
res = [];
for (const frag of tmp) {
res.push(`> ${frag}`);
}
return res.join('\n');
}
let str = addPrefix`Lorem ipsum dolor sit amet,
consectetur adipiscing elit.
Vestibulum pellentesque`;
console.log(str);
One-liner with Array.prototype.map() (see Miguel's comment)
const addPrefix = str => str[0].split('\n').map(s => `> ${s}`).join('\n');
let str = addPrefix`Lorem ipsum dolor sit amet,
consectetur adipiscing elit.
Vestibulum pellentesque`;
console.log(str);

To insert something at the beginning of each line of a string, use replace with the regular expression /^/gm, i.e. str.replace(/^/gm, prefix):
const Formatter = ({text, prefix}) => (
<textarea>{text.replace(/^/gm, prefix)}</textarea>
);
const text = `Lorem ipsum dolor sit amet,
consectetur adipiscing elit.
Vestibulum pellentesque`;
const prefix = '> ';
ReactDOM.render(<Formatter text={text} prefix={prefix}/>, document.querySelector('div'));
textarea { font-family: monospace; width: 100%; height: 4em; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div></div>

Related

How to select entire lines of text when selection partially covers multiple lines

In the example below place the cursor anywhere in the middle of two lines, eg. from 'ipsum' to the following 'lorem'. The following words will be selected: ipsum dolor sit lorem
On clicking the button I need to get the full lines in the selection. In the above example I should retrieve the following words:
lorem ipsum dolor sit lorem ipsum
Does anyone know how I can do this?
$('button').on('click', function() {
var sel = window.getSelection();
sel.modify('move', 'backward', 'paragraphboundary');
sel.modify('extend', 'right', 'paragraphboundary');
});
div {
white-space: pre-wrap;
outline: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div contenteditable>lorem ipsum
dolor sit
lorem ipsum
lorem ipsum
dolor sit
lorem ipsum
</div>
<br>
<button>CLICK</button>

Scrolling Text in DIV on Keydown

I want to create a scroll effect on the div such that when the SPACE key is pressed, the first span moves up out of visibility and the span become visible.
HTML
<div class="scroll-div">
<span class="item1">Lorem ipsum dolor sit amet consectetur, adipisicing elit. Rerum, beatae.</span>
<span class="item1">Lorem ipsum dolor sit amet consectetur, adipisicing elit. Rerum, beatae.</span>
<span class="item1">Lorem ipsum dolor sit amet consectetur, adipisicing elit. Rerum, beatae.</span>
<span class="item1">Lorem ipsum dolor sit amet consectetur, adipisicing elit. Rerum, beatae.</span>
</div>
CSS
.scroll-div{
width: 150px;
height: 100px;
overflow-y: scroll;
}
JS
const scrollDiv = document.querySelector('.scroll-div');
scrollDiv.addEventListener('keydown', event => {
if(event.key == ' '){
...scroll up;
}
})
PS: If it can be done with CSS alone, I would prefer that.
You must use at the end of each .
/* Your Modified Javascript */
<script language="javascript">
//Get the no of elements having the same classname.
var items = document.getElementsByClassName("item1").length;
i=0; //set a variable to get the current element.
const scrollDiv = document.querySelector('.scroll-div');
scrollDiv.addEventListener('keydown', event => {
if(event.key == ' '){
//Scroll to each element on every key press
document.getElementsByClassName("item1")[i].scrollIntoView({behavior: "smooth"});
i++; //Increment the value of i to jump to next <span>
}
});
</script>
Hope this Code will Solve your issue 😊

How to render textarea in correct size and auto expand while typing?

I have a textarea and I would like it to load in the size of the value that is already there, and also to automatically expand as I continue typing.
I found these two pieces of JavaScript code work well separately, but when I put them together, one of them stops working. How do I bind them together?
$("textarea").height( $("textarea")[0].scrollHeight );
$(document)
.one("focus.autoExpand", "textarea.autoExpand", function() {
var savedValue = this.value;
this.value = "";
this.baseScrollHeight = this.scrollHeight;
this.value = savedValue;
})
.on("input.autoExpand", "textarea.autoExpand", function() {
var minRows = this.getAttribute("data-min-rows") | 0,
rows;
this.rows = minRows;
rows = Math.ceil((this.scrollHeight - this.baseScrollHeight) / 10);
this.rows = minRows + rows;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea name="textarea" class="autoExpand" rows='1' data-min-rows='1'>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</textarea>
You can use this simple jQuery codes to accomplish that.
$('#textarea').on('change keyup keydown paste cut', 'textarea', function () {
$(this).height(0).height(this.scrollHeight);
}).find('textarea').change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='textarea'>
<textarea name="textarea" class="autoExpand" rows='1' data-min-rows='1'>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</textarea></div>
As you can see, a JavaScript solution can complex. You can simply use a <span> which adjusts its size automatically as you described, and make it editable by adding the contenteditable="true" property:
div {
width: 200px;
}
span {
border: 1px solid #999;
padding: 3px;
font-family: Arial;
}
<div>
<span contenteditable="true">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</span>
</div>
However, if you want to submit the value as part of the form, you'll have to do so by yourself in JavaScript, but that's relatively easy. You can add a hidden field, and assign the value of the span to the hidden field in the onsubmit event of the form. The hidden field will be then submitted with the form.

jQuery wrap closing tag until the same opening tag

I have this markup:
<h2>my title here</h2>
Lorem ipsum dolor sit amet
<h2>my title here</h2>
consectetur adipisicing elit quod tempora
I would like to select all the content between the closing </h2> until the next opening <h2> and wrap it as a div with a class, for example:
<h2>my title here</h2>
<div class="my-class">Lorem ipsum dolor sit amet</div>
<h2>my title here</h2>
<div class="my-class">consectetur adipisicing elit quod tempora</div>
var a = $('body').first().contents().filter(function() {
return this.nodeType == 3;
}).wrap('<div class="my-class">');
console.log(a)
.my-class{
color:red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h2>my title here</h2>
Lorem ipsum dolor sit amet
<h2>my title here</h2>
consectetur adipisicing elit quod tempora
DO something like this
$('h2').each(function(idx, elm) {
var $elm = $(elm);
// select text after h2
var next = $elm[0].nextSibling;
var val = next.nodeValue.trim();
// create div , add text to it
var $div = $('<div>');
$div.text(val);
// remove previously selected text nodes
next.remove();
// add divs after h2
$elm.after($div);
});
div {
color: blue;
font-size: 1.8em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<h2>my title here</h2>
Lorem ipsum dolor sit amet
<h2>my title here</h2>
consectetur adipisicing elit quod tempora

readmore javascript plugin first item open

I'm using this wonderful plugin and would like to know how I can set the first item to be open and the rest closed.
Any idea?
Javascript
var options = {
moreLink: '<a class="read_more_link" href="#">more...</a>',
lessLink: '<a class="read_less_link" href="#">less...</a>',
heightMargin: 50,
sectionCSS: 'display: inline-block; width: 100%;',
};
$('.content-top-wide, .content-bottom-item').each(function(){
var el = $(this), content = el.find('div:first,span:first,p:first, article:first'), maxHeight = 0;
if (content.length) {
maxHeight = content.outerHeight();
content.prevAll().each(function(){
maxHeight += $(this).outerHeight(true);
});
// set maxHeight to 200px if the element has hight greater than 200
options.maxHeight = Math.min(200, maxHeight);
el.readmore(options);
};
});
HTML
<div class="content-bottom pull-left">
<h2>Title</h2>
<div class="content-bottom-item pull-left">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Natus, consequatur inventore iure aliquam praesentium molestiae facilis labore! Magni, dolorem, ex? Lorem ipsum dolor sit amet, consectetur adipisicing elit. Natus, consequatur inventore iure aliquam praesentium molestiae facilis labore! Magni, dolorem, ex?
</div>
</div>
Read the documentation of the plugin: https://github.com/jedfoster/Readmore.js ?
Adding "startOpen: false" to the options of the first item should solve your problem.
I managed doing this by adding an if statement:
if ( i == 0) {
options.startOpen = true;
} else {
options.startOpen = false;
}
el.readmore(options);
Here is a working version in case someone need: http://jsfiddle.net/brunodd/pvZ8H/

Categories