Wrapping text to the next line after a fullstop or condition? - javascript

Is it possible to move text to the next line after a full stop?
For example with a standard h1 header - 'This is a very. Very. Big header.'
But I want my headers to move to the next line after a fullstop -
'This is a very.
Very.
Big header.'
My goal is to have every title h1 fetched from an API to for formatted so the line wraps every time there is a fullstop '.'
Code:
<div className='quote-wrapper'>
<h1 className='quote'>{currentQuote.quote}</h1>
</div>

I don't believe there is a way this can be achieved as a CSS style or HTML property. Look into word-wrap and text-overflow incase they work for you, though.
In JavaScript, this is easy. Just find all the elements you want to change (like all h1's, get their current text with .innerText or .innerHtml, and then set their current text to be their old text but replace all the periods with newlines.
document.querySelectorAll("h1").forEach((x) => {
x.innerText = x.innerText.replace(/\./g, "\n")
})
Here, document.querySelectorAll("h1") gets a list of all h1's on the page. You could make it something like ".quote" to select by class, etc.
forEach(...) takes a function (the (x) => {...} thing) and applies it to each item in the list.
In our function x.innerText is the text inside the h1 element and replace replaces everything matching the first argument (/\./g) with the second argument ("\n"). Here, /\./g is the regular expression for "all periods" and "\n" is the newline character.
Edit:
It looks like you are using React so you don't actually need to do anything with a querySelector. Just perform the replace on currentQuote.quote right before you put it into the DOM

You can do it by using the split method.
Here is how i did it.
https://code.sololearn.com/W85wKQly9I7a/?ref=app

Related

Parsing plain text Markdown from a ContentEditable div

I know there are other questions on editable divs, but I couldn't find one specific to the Markdown-related issue I have.
User will be typing inside a ContentEditable div. And he may choose to do any number of Markdown-related things like code blocks, headers, and whatever.
I am having issues extracting the source properly and storing it into my database to be displayed again later by a standard Markdown parser. I have tried two ways:
$('.content').text()
In this method, the problem is that all the line breaks are stripped out and of course that is not okay.
$('.content').html()
In this method, I can get the line breaks working fine by using regex to replace <br\> with \n before inserting into database. But the browser also wraps things like ## Heading Here with divs, like this: <div>## Heading Here</div>. This is problematic for me because when I go to display this afterwards, I don't get the proper Markdown formatting.
What's the best (most simple and reliable) way to solve this problem as of 2015?
EDIT: Found a potential solution here: http://www.davidtong.me/innerhtml-innertext-textcontent-html-and-text/
if you check the documentation of jquery's .text() method,
The result of the .text() method is a string containing the combined text of all matched elements. (Due to variations in the HTML parsers in different browsers, the text returned may vary in newlines and other white space.)
so getting whitespaces is not guaranteed in all browsers.
try using the innerText property of the element.
document.getElementsByClassName('content')[0].innerText
this returns the text with all white spacing intact. But this is not cross browser compatible. It works in IE and Chrome, but not in Firefox.
the innerText equivalent for Firefox is textContent (link), but that strips out the whitespaces.
This is what I've been able to come up with using that link I posted above in my edit. It's in Coffeescript.
div = $('.content')[0]
if div.innerText
text = div.innerText
else
escapedText = div.innerHTML
.replace(/(?:\r\<br\>|\r|\<br\>)/g, '\n')
.replace(/(\<([^\>]+)\>)/gi, "")
text = _.unescape(escapedText)
Basically, I'm checking whether or not innerText works, and if it doesn't then we do this other thing where we:
Take the HTML, which has escaped text.
Replace all the <br> tags with line breaks.
Strip out any tags (escaped ones won't be stripped, i.e. the stuff the user types).
Unescape the escaped text.

How to detect the first word of a string in jQuery?

I currently have a problem related to jQuery.
For the whole story, I'm creating some tooltips, I center them right under the desired trigger using css.
Everything is working, but here is the problem :
I have a <p> tag with some text in it.
The tooltip is generated by the first word of the string, and because of the alignment, the first half of the tooltip is outside of the viewport.
So it looks like this :
And I want to be able to target the first-word with jQuery, in order to write something like :
if( isFirstWord == true ) {
tooltip.css('left','xx%')
}
That will let me position the tooltip properly, only if it belongs to the first word.
I hope you guys got my question, if not, just drop a comment, I'll be glad to give you more informations about it.
One way:
$('something').each(function(){
var me = $(this);
me.html(me.html().replace(/^(\w+)/, '<span>$1</span>'));
});
Basically, for each match (something) you replace the first word with itself ($1) wrapped in tags. The character class \w matches letters, digits, and underscores (thus defining what a "word" is - you may need another definition).
The solution already exist here: First Word in String with jquery

Automatically recognize an image from textarea (like StackOverflow)

I would like to create my own "editor" (only code-view, no WYSIWYG) and I have a problem with inserting images. Uploading and selecting images is done via blueimp-jQuery-File-Upload.
What I would like to do is insert them into my textarea in the same way that StackOverflow does it (so without some fancy galleries, modules etc). I upload it and it automatically add's in a textarea in this format
![imageDescription][1]
[1]: http://i.stack.imgur.com/image.jpg
My question is how to do (probably with jQuery/JavaScript) automatic recognition if some image is present in my text area (so if I have these two lines in my textarea), below textarea those images are displayed (or their links) but if I delete them (text lines) - those links/images below disappear.
Probably I should do some "scanning" line by line on every keypress? Maybe with regular expression so if it's true (for both lines) - then display the image below, instead it's just a regular text.
If you want to show those images instantly below your editor, you have no choice but binding that thing to an keypress event. When you get the text you could do some regex action to catch the image and insert it into an <img src="my image">. After that check after every press if the imageurl is still present in that editor (maybe a history is a good choice). If not, delete the <img> tag.
If it's still needed, here's some reference that I made.
Javascript regex replacements:
.replace(new RegExp("\_img_([^ ].+?[^ ])\_img_", "g"),"<img src='$1' />")
Its actually a pattern that could be applied to just about any tag. The regex is as follows:
.replace(new RegExp("\___what ever signifier here ___([^ ].+?[^ ])\_____end sign____", "g"),"<tag>$1</tag>")
*remember to escape special characters in the regex like * with twp forward slashs like so: \\*
also, if you want to add more parameters, just add another ([^ ].+?[^ ]) block and then name where the next parameter will go with $2 like so:
.replace(new RegExp("\\[([^ ].+?[^ ])\\]\\(([^ ].+?[^ ])\\)", "g"),"<a href='$1'>$2</a>")
notice that I escaped [ ] ( ) with double forward slashes.
See it in action: http://jsfiddle.net/xwTGr/

jQuery match first letter in a string and wrap with span tag

I'm trying to get the first letter in a paragraph and wrap it with a <span> tag. Notice I said letter and not character, as I'm dealing with messy markup that often has blank spaces.
Existing markup (which I can't edit):
<p> Actual text starts after a few blank spaces.</p>
Desired result:
<p> <span class="big-cap">A</span>ctual text starts after a few blank spaces.</p>
How do I ignore anything but /[a-zA-Z]/ ? Any help would be greatly appreciated.
$('p').html(function (i, html)
{
return html.replace(/^[^a-zA-Z]*([a-zA-Z])/g, '<span class="big-cap">$1</span>');
});
Demo: http://jsfiddle.net/mattball/t3DNY/
I would vote against using JS for this task. It'll make your page slower and also it's a bad practice to use JS for presentation purposes.
Instead I can suggest using :first-letter pseudo-class to assign additional styles to the first letter in paragraph. Here is the demo: http://jsfiddle.net/e4XY2/. It should work in all modern browsers except IE7.
Matt Ball's solution is good but if you paragraph has and image or markup or quotes the regex will not just fail but break the html
for instance
<p><strong>Important</strong></p>
or
<p>"Important"</p>
You can avoid breaking the html in these cases by adding "'< to the exuded initial characters. Though in this case there will be no span wrapped on the first character.
return html.replace(/^[^a-zA-Z'"<]*([a-zA-Z])/g, '<span class="big-cap">$1</span>');
I think Optimally you may wish to wrap the first character after a ' or "
I would however consider it best to not wrap the character if it was already in markup, but that probably requires a second replace trial.
I do not seem to have permission to reply to an answer so forgive me for doing it like this. The answer given by Matt Ball will not work if the P contains another element as first child. Go to the fiddle and add a IMG (very common) as first child of the P and the I from Img will turn into a drop cap.
If you use the x parameter (not sure if it's supported in jQuery), you can have the script ignore whitespace in the pattern. Then use something like this:
/^([a-zA-Z]).*$/
You know what format your first character should be, and it should grab only that character into a group. If you could have other characters other than whitespace before your first letter, maybe something like this:
/.*?([a-zA-Z]).*/
Conditionally catch other characters first, and then capture the first letter into a group, which you could then wrap around a span tag.

Highlight specific strings in a given long string in Javascript

I have a long string, and a list of other strings, which I need to mark in the long string.
Say we have abcdefghijk and the strings I need to mark are ghi and abc.
What is the simplest way to do it in Javascript and CSS? I thought about using the exec() method that will return the starting index of the string in the long string.
Then, I'd have the starting index and the size of the string. So, I could find it in the long string. How could I highlight it? Maybe using CSS?
You can try this jQuery plugin. It's really straightforward...
How to use it?
1 - Download the plugin
jquery.highlight-3.js (2 KB) and reference it in your page just after jQuery.
2 - Style the highlight class
Create an entry in your CSS sheet:
.highlight { background-color: yellow }
3 - Highlight term/phrase
Call the highlight function with the text to highlight. To highlight all occurrences of “ghi” (case insensitive) that are within the form element, use the following code:
$('form').highlight('ghi');
4 - Remove highlighting
The highlight can be removed from any element with the removeHighlight function. In this example, all highlights under the element with the ID highlight-plugin are removed.
$('#highlight-plugin').removeHighlight();
Well if you know the index of the start of the string and the length you could just simply put span tags around it. So your HTML would look like:
<span class="highlight">abc</span>def<span class="highlight">ghi</span>jk
And then you'd style the span in your CSS:
.highlight
{
background-color:yellow;
}

Categories

Resources