Simple JS code for highlighting search text in a paragraph - javascript

I am trying to rewrite this code to suit my needs, but I am lost in all the replacing magic that the auther of the Fiddle does. Here's my modified fiddle.
My goal is to find all occurrances of "a" letter in the paragraph and highlight them. I just can't figure out why my letters are just being replaced by 1$ instead of being highlighted. Can anyone help me with this ?
HTML
<div id="searchtext">
<p>I want to highlight all "a" letters in this paragraph</p>
</div>
JS
$(document).ready(function() {
var text = 'a';
var query = new RegExp(text, "gim");
var e = document.getElementById("searchtext").innerHTML;
var enew = e.replace(/(<span>|<\/span>)/igm, "");
document.getElementById("searchtext").innerHTML = enew;
var newe = enew.replace(query, "<span>1$</span>");
document.getElementById("searchtext").innerHTML = newe;
});
CSS:
#searchtext span {
background-color: #FF9;
color: #555;
}

Use \$& instead
$(document).ready(function() {
var text = 'a';
var query = new RegExp(text, "gim");
var e = document.getElementById("searchtext").innerHTML;
var enew = e.replace(/(<span>|<\/span>)/igm, "");
document.getElementById("searchtext").innerHTML = enew;
var newe = enew.replace(query, "<span>\$&</span>");
document.getElementById("searchtext").innerHTML = newe;
});
#searchtext span {
background-color: #FF9;
color: #555;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="searchtext">
<p>I want to highlight all "a" letters in this paragraph</p>
</div>
More information about $&

Related

How to display text with multiline from JavaScript to the HTML

I want to display multi line text, from JavaScript to the HTML using looping. The text position is after display the image. The text result should be like
Place ..... // newline price ....
<div id="display">
<script type="text/javascript" src="../controler/package.js"></script>
</div>
var display = document.getElementById('display');
function buildImages(images,place,k,price){
var last=document.createElement("IMG");
last.src=images;
last.width=800;
last.height=600;
last.style.marginTop=30;
display.appendChild(last);
var x = document.createElement("H3");
var t = document.createTextNode("Place:"+place);
var z = document.createTextNode(" price:"+price);
x.appendChild(t);
x.appendChild(z);
display.insertBefore(x,display.childNodes[k]);
The cleanest way is probably to do the same thing you would do in HTML: wrap your text nodes in <p> elements.
Wrapping the text in an HTML element will always help you later to customize style or whatever!
Raw text nodes are not that convenient.
There are multiple ways to achieve this. One is using br tags
var x = document.createElement("H3");
var t = document.createTextNode("Place:"+place);
var br = document.createElement("BR");
var z = document.createTextNode(" price:"+price);
x.appendChild(t);
x.appendChild(br);
x.appendChild(z);
Another could be using a pre tag
var x = document.createElement("H3");
var t = document.createTextNode("Place:"+place + "\n price:" + price);
x.appendChild(t);
Or you could could use two spans that have display: block;
var x = document.createElement("H3");
var t = document.createElement("SPAN");
t.style.display = "block";
t.innerText = "Place:" +place;
var z = document.createElement("SPAN");
z.style.display = "block";
z.innerText = "Price:" +price;
var z = document.createTextNode(" price:"+price);
x.appendChild(t);
x.appendChild(z);
It can not work like this by design. if you do not use
<pre>
or
<code>
if you want to use line feeds or if you prefer other tags like
<p>
then you has to use at least
<br>
by this you can still format the text as you wish. Will look usually a bit messy. I would use a table.

Adding br tag in innerHTML between text and image

In my javascript program I have created div and added image and some hardcoded text in div by using innerHTML. But I am trying to add dynamic br tag between text and image. First text should be displayed then want to line break and then image should be displayed. So created br and added but somehow it doesn't work. Can anyone correct me ?
code:
function useInnerHTML() {
var movieText2 = prompt("One of my favourite movies");
var textNode = document.createTextNode(movieText2);
ele.appendChild(textNode);
document.body.appendChild(ele);
var newDiv2 = document.createElement("div");
var br = document.createElement("br");
newDiv2.className = "green";
var pic = "A picture is worth a thousand words";
var text2 = '<img src=\'https://i.stack.imgur.com/meXYL.png\'>';
newDiv2.innerHTML = pic + text2;
document.body.appendChild(newDiv2);
document.body.appendChild(br);
}
useInnerHTML();
.pink {
background-color: pink;
}
.green {
background-color: #71e887;
}
my output:
![output][1]
Simply use
pic = "A picture is worth a thousand words <br>";
since by using .innerHTML the <br> tag will not be escaped and actually embedded into the HTML as a breakline Element.
Or
Use Template strings and insertAdjacentHTML
function addNewMovie() {
var movieName = prompt("One of my favourite movies").trim(); // Trim it!
if(!movieName) return; // do nothing if empty!
var movieTemplate = `
<div class="movie">
<h1>${movieName}</h1>
<div class="green">
A picture is worth a thousand words<br>
<img src='//placehold.it/100x100/0bf'>
</div>
</div>
`;
document.body.insertAdjacentHTML("beforeend", movieTemplate);
}
<button onclick="addNewMovie()">ADD NEW MOVIE</button>
...cleaner, nicer.
You are adding the <br> after the picture, try doing it like this:
newDiv2.innerHTML = pic + br + text2;
document.body.appendChild(newDiv2);

How to replace text between tags only

I have multiple h2 tags and every tag contains text and has a custom attribute called data-options. This attribute has multiple options separated by commas and one of these options is the h2 tag text itself.
HTML:
<h3 id='test' data-options='happy,sad,fantastic'>sad</h3>
<h3 id='test2' data-options='1,2,3,4'>3</h3>
jQuery:
var indexArray = ['happy','1'];
$('h3').each(function(i){
var $this = $(this),
value = $this.text(),
code = $('body').html();
code = code.replace(value, indexArray[i]);
$('body').html(code);
});
This is what I expect:
<h3 id='test' data-options='happy,sad,fantastic'>happy</h3>
<h3 id='test2' data-options='1,2,3,4'>1</h3>
Instead I get this:
<h1 id="test" data-options="happy,happy,fantastic">sad</h1>
<h3 id="test2" data-options="1,2,3,4">3</h3>
As you can see the script changes the first text it encounters, not the one inside the tags.
This is a working demo for the script : http://jsfiddle.net/fs1sfztx/
It makes no sense to do a replace unless you're searching. Which means you have to be provided what to search for and what to replace it with. So far only the text to in the h3 is given.
Assuming that each index in indexArray matches the index of each h3 element, then you can compare the current indexArray element indexArray[i] with each of the words in the corresponding elements data-options attribute. When a matches, set the innerText prop to that word.
var indexArray = ['happy','1'];
$('h3').text( function( i, txt ) {
var that = $(this);
var ntxt = txt;
$.each( that.data('options').split(','), function( j, u ) {
indexArray[i] !== u || (ntxt = u);
});
return ntxt;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3 id='test' data-options='happy,sad,fantastic'>sad</h3>
<h3 id='test2' data-options='1,2,3,4'>3</h3>
If all you wanted is to play with the replace method, then you could use something like this:
var indexArray = ['happy','1'];
var allhtml = $('body').html();
$('h3').each( function( i ) {
var txt = $(this).text();
var re = new RegExp( '>' + txt + '<', 'g' );
allhtml = allhtml.replace( re, '>' + indexArray[i] + '<' );
});
$('body').html( allhtml );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3 id='test' data-options='happy,sad,fantastic'>sad</h3>
<h3 id='test2' data-options='1,2,3,4'>3</h3>

How to replace a text with coloured text using javascript

I am having this text in text area.
{color:#c91d1d}Hello{color}
when it is submitted, i want the text between {} tags to be shown in color specified inside {} tag with color:
how can i do so in javascript
use javascript built in function to extract color code
var colorValue = str.substring(7, 7);
it extract 7 characters from 7th position.
now change the color using:
document.getElementById("myH2").style.color = colorValue;
I hope this will work
You can use a regex like
$('#input').on('input', function() {
$('#result').html(this.value.replace(/\{color:(.*?)\}(.*?)((\{color\})|$)/g, '<span style="color:$1">$2</span>'));
}).triggerHandler('input');
textarea {
width: 100%;
min-height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea id="input">{color:#c91d1d}Hello{color} - {color:green}hi{color}</textarea>
<div id="result"></div>
Arun is right, and if you just need to get "Hello" from "{color:#c91d1d}Hello{color}" string you can do it like this
var justtext="{color:#c91d1d}Hello{color}".match(/\{.*\}(.*)\{.*\}/)[1];
For full replacement of text in textarea here's the code. Suppose textarea has id attribute "textarea1", change it with your id.
var textwithcolor =$("#textarea1").text();
var justtext=textwithcolor.match(/\{.*\}(.*)\{.*\}/)[1];
$("#textarea1").text(justtext);
this is how it can be done
No need to use regular expressions.
try this
var str = $('#t').text();
var res = str.substring(7, 14);
newstr = str;
while (newstr.indexOf("{color}") > -1) {
newstr = newstr.replace("{color}", "</div>");
}
while (newstr.indexOf("{color:") > -1) {
newstr = newstr.replace("{color:", "<div style='color:");
newstr = newstr.replace("}", "'>");
}
document.getElementById("t").innerHTML = newstr;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="t">{color:#c91d1d}Hello{color}
{color:red}How{color} {color:yellow}are{color} {color:green}you{color}
</div>

Find the length of a string after the first occurrence of a defined sub-string

So, I have this textarea in html and I am trying to implement something like twitter.
Everytime a user types in '#' I want to highlight the word and at the end of word I want to display a letter count. So for example, " Hi my name is #user123(7) , whats your name?"
I already have the highlighting taken care of, but I am currently lost on the letter count part.
Here is my HTML
<div id="inputback" class="format"></div>
<textarea id="input" class="format"></textarea>
Javascript
var textarea = document.getElementById("input");
var hashflag = 0 ;
var textlength;
textarea.onkeydown = function(e){
textarea.style.height = "";
textarea.style.height = textarea.scrollHeight + "px";
textlength = textarea.value.length;
var str = textarea.value;
str = str.replace(/(\s)([#]\w*)/g, "$1<b>$2</b>");
$('#inputback').html(str);
}
Here is my CSS
.format
{
font: 9pt Consolas;
}
#input { border: 1px solid black; background: transparent; z-index: 10; }
#inputback {
color: transparent;
position: absolute;
top: 0px
}
#inputback b
{
color: black;
background-color: #808080;
font-weight: normal;
}
Here is my jsfiddle of what i have accomplished.
http://jsfiddle.net/gjqWy/115/
Thank you in advance!
P.S I dont want to use any plugins or Jquery. Just plain Javascript/html/css
.replace can also take a function as its second paramter:
str = str.replace(/(^|\s)#(\w+)/g,function(_,a,b) {
// _ represents the full match - we don't need it here
// a is the first subpattern
// b is the second subpattern
return a+"<b>#"+b+"</b>("+b.length+")";
});
I adjusted your regex a bit. Now it will work even if the hash is at the start of the string, and also I took the hash out of the captured group becase a) it's constant, and b) you want the length of the second capture group, and this makes it easier.
<form id="testForm">
<input id="A1" type="text"></input>
<div id="vsA1" class="inputTextSummery">charaters reamining: 40</div>
</form>
<script type="text/javascript">
function wordCount(_input, _limit, _summary)
{
var limit = _limit; //set limit of charater
var inputDiv = "#"+_input; //inout div id
var displayDiv = "#"+_summary; //display summary div id
var currentWordCount = 0; //defualt current charater count
$(inputDiv).keyup(function(){ //
currentWordCount = $(inputDiv).val().length;
var charLeft = limit - currentWordCount;
if(charLeft >= 0){
$(displayDiv).html("charaters reamining: "+ (limit - currentWordCount));
}else{
$(displayDiv).html("Input has exceed limit!");
}
});
}
wordCount("A1", 40, "vsA1");
Use the JavaScript .indexOf method to find the first occurrence # in the value of your form. What it does is find the first occurrence of '#' in the string your checking and it returns the place of it.
E.G.
var string = "This is stackoverflow";
var start = string.indexOf('is'); //Will return as 5
After you get that sorted all you will need to do it grab the values after it. Like this
var string = "This is stackoverflow";
var start = string.indexOf('is') + 2; //7 (You add 2 because its a 2 letter word)
var end = string.length; //20
var newstring = string.substr(start, end);
You can take this information and apply it to your forum by replacing var string with document.getElementById('inputidhere').value; And then go from there!
Goodluck! Hope this helped you.

Categories

Resources