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;
}
Related
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
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
Setup:
I'd like to output some text that shows visible spaces, linebreaks, etc
(For the purpose of displaying strings for debug purposes (or for say a rich-text editor))
ie, id like to make the following type of substitutions
" " -> "<span class="whitespace">·</span>"
"\r" -> "<span class="whitespace">\\r</span>"
"\n" -> "<span class="whitespace">\\n</span>"
perhaps the following CSS rule could be defined
/*display whitespace chars as a light grey*/
.whitespace { color:#CCC; }
so that
this two line
string
would be displayed as
this·two·lined\n
\t string
The Question:
Is it possible so that when the above "visual-whitepace" text is selected / copied-to-clipboard... it copies without the whitespace markup?
Is there some CSS property to display x, but copy y?
javascript hack?
special whitespace-font?
other?
<style>.paragraph-marker:after { content: "\B6" }</style>
<p>Foo<span class="paragraph-marker"></span></p>
<p>Bar<span class="paragraph-marker"></span></p>
The :after is a "pseudo-selector" which matches a pseudo-node that immediately follows the affected element.
The content property can be used with these pseudo-nodes to specify the textual content of them. It comes in handy when specifying quotation marks before and after quoted sections, or list separators like commas in semantic HTML <ol> which you don't want to display in bullet format.
It should come in handy for your use case since browsers don't deal with pseudo-nodes when converting a DOM selection stored in the clipboard to plain text on paste.
http://codepen.io/msvbg/pen/ebgrj
Works fine in the latest version of Chrome. Flip the showWhitespace variable to try it both ways. It works by sticking a visible whitespace layer underneath the text layer, and only the top-most layer is copied by default.
I want to detect and style a special letter .
for example something like this
:
body["p"] /
body["2"]
how can I do this?
thanks
You could do this on a node-by-node basis with a fairly simple replace, but it wouldn't scale very well.
Given the markup:
<p>Peter Rabbit ate all of Potter's pickling cukes.</p>
If you wanted to add a style to all of the letters p in this text, you could select the paragraph node and add spans around any p (assuming a single paragraph):
var graf = document.getElementsByTagName('p')[0];
graf.innerHTML = graf.innerText.replace(/(p)/gi,'<span class="fancy">$1</span>');
That said, this would only work on plain text nodes; if you had, for example, a span tag already in the p tag, it'd get mucked up by the replace.
You cannot with CSS. The only non-element (css-created) pseudo-elements are ::first-line and ::first-letter.
However, you could search with JS through the DOM and create tags around the letters to be highlighted. Check highlight words in html using regex & javascript - almost there for how to do that.
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.