I wrote this function which takes in a word as input and puts it in a <b> tag so that it would be bold when rendered in HTML. But when it actually does get rendered, the word is not bold, but only has the <b> tag arround it.
Here is the function:
function delimiter(input, value) {
return input.replace(new RegExp('(\\b)(' + value + ')(\\b)','ig'), '$1<b>$2</b>$3');
}
On providing the value and input, e.g. "message" and "This is a test message":
The output is: This is a test <b>message</b>
The desired output is: This is a test message
Even replacing the value with value.bold(), returns the same thing.
EDIT
This is the HTML together with the JS that I m working on:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Test</title>
<script>
function myFunction(){
var children = document.body.childNodes;
for(var len = children.length, child=0; child<len; child++){
if (children[child].nodeType === 3){ // textnode
var highLight = new Array('abcd', 'edge', 'rss feeds');
var contents = children[child].nodeValue;
var output = contents;
for(var i =0;i<highLight.length;i++){
output = delimiter(output, highLight[i]);
}
children[child].nodeValue= output;
}
}
}
function delimiter(input, value) {
return unescape(input.replace(new RegExp('(\\b)(' + value + ')(\\b)','ig'), '$1<b>$2</b>$3'));
}
</script>
</head>
<body>
<img src="http://some.web.site/image.jpg" title="knorex"/>
These words are highlighted: abcd, edge, rss feeds while these words are not: knewedge, abcdefgh, rss feedssss
<input type ="button" value="Button" onclick = "myFunction()">
</body>
</html>
I'm basically getting the result of the delimiter function and changing the nodeValue of a child node.
Is it possible there is something wrong with the way I'm taking back what the function is returning to me?
This is what I do:
children[child].nodeValue = output;
You need to have the markup processed as HTML, instead of being just set to replace existing content in a text node. For this, replace the statement
children[child].nodeValue= output;
by the following:
var newNode = document.createElement('span');
newNode.innerHTML = output;
document.body.replaceChild(newNode, children[child]);
Related
I'm very new to JavaScript so I apologize if this question has an extremely obvious answer. What I'm trying to do is pass the name of a text box in HTML to a function in Javascript via an onclick button. The goal of the function is to test a given string and highlight it based on certain parameters (for my testing, it is simply length).
There are multiple weird odds and ends within the functions that I'm aware of and working on, I know the functions work as when I remove the parameters and call the code text box directly, it prints exactly what I expect it to. But I want to be able to pass multiple text boxes without needing a specific function per box.
The code I have is as follows. I've included all of it in case the mistake was made somewhere I didn't expect it to be.
<!DOCTYPE html>
<html>
<head>
<style>
.highlight {
background-color: yellow;
}
</style>
</head>
<body>
<label for="wordOne">Word One</label><br>
<input type="text" id="wordOne" name="wordOne"><br>
// Pass the value for the wordOne textbox to verify function
<button type="button" onclick="verify(wordOne,this)">Check</button><br><br>
<label for="wordTwo">Word Two</label><br>
<input type="text" id="wordTwo" name="wordTwo"><br>
// Pass the value for the wordTwo textbox to verify function
<button type="button" onclick="verify(wordTwo,this)">Check</button><br><br>
<p id="test"></p><br>
<p id="error"></p>
<script>
// Highlights any code in a given line.
function highlight(text,id,begin,end) {
// document.getElementById("error").innerHTML = "TEST";
var inputText = document.getElementById(id);
var innerHTML = inputText.innerHTML;
var index = innerHTML.indexOf(text)+begin;
if (index >= 0) {
innerHTML = innerHTML.substring(0,index) + "<span class='highlight'>" + innerHTML.substring(index,index+text.length) + "</span>" + innerHTML.substring(index + text.length-end);
inputText.innerHTML = innerHTML;
return string;
}
}
function verify(button,el){
var begin=1;
var end=1
var id="test";
var string = document.getElementById(button).value;
var len=string.length;
if(len>5)
{
document.getElementById(id).innerHTML = string +" "+len;
highlight(string,id,begin,end);
}
else
{
document.getElementById(id).innerHTML = string;
}
}
</script>
</body>
</html>
I apologize again if this is extremely obvious but I'm honestly not sure what I'm doing wrong. Thanks in advance for any help!
You can get the name of the textbox by the attribute
var x = document.getElementsByTagName("INPUT")[0].getAttribute("name");
And then use it in your function as
var x = document.getElementsByTagName("INPUT")[0].getAttribute("name");
function highlight(x,id,begin,end) {
// document.getElementById("error").innerHTML = "TEST";
var inputText = document.getElementById(id);
var innerHTML = inputText.innerHTML;
var index = innerHTML.indexOf(text)+begin;
if (index >= 0) {
innerHTML = innerHTML.substring(0,index) + "<span class='highlight'>" + innerHTML.substring(index,index+text.length) + "</span>" + innerHTML.substring(index + text.length-end);
inputText.innerHTML = innerHTML;
return string;
}
}
NOTE : By [0] it means the first one that is the first textbox.
I need help to sanitize my HTML text provided by user. I have following HTML code:
var htmlStr = `<p id="test" class="mydemo">TEhis is test</p>
<pre class="css">
<html>
<body class="test"></body>
</html>
</pre>`;
I want to remove ID, Class or any attribute from all the tags OTHER then <PRE> and <CODE> tags using plain JavaScript.
I tried following but not getting proper output:
sanitizeHtml(html: any) {
let temp = document.createElement('div');
temp.innerHTML = html;
// let t1 = temp.querySelectorAll('*');
temp.querySelectorAll('*').forEach(node => {
if(node.nodeName !== 'PRE') {
return node.removeAttribute('id');
}
})
console.log(temp);
// return html.replace(/\s*(\w+)=\"[^\"]+\"/gim, '').replace(/<script>[\w\W\s\S]+<\/script>/gim);
}
Please let me know if you need further information on it.
This is a little mechanical, and perhaps not the optimal solution, however you could achieve this by chaining .replace() with the following regular expressions to sanitise your HTML string as needed:
function sanitizeHtml(html) {
var htmlSanitized = html
.replace(/<pre[\w\s"=]*>/gi, function(match) {
// Add a place holder to attrbitues on pre elements to prevent
// removal of these in subsequent step
return match.replace(/=/gi, 'EQUALS')
})
.replace(/\w+="\w+"/gi,'')
.replace(/\s+>/gi,'>')
.replace(/EQUALS/i,'=')
return htmlSanitized;
}
var htmlStr = `<p id="test" class="mydemo">TEhis is test</p>
<pre class="css">
<html>
<body class="test"></body>
</html>
</pre>`;
console.log(sanitizeHtml(htmlStr));
I need help with how to code this program in javascript. The javascript code should load a character from a box and a number (N) from another box. When you press a button, N rows prints each one of those with N characters (same characters that are loaded are printed). Before printing, check that it is only available a character in the box where characters are to be entered.
code in html:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<p id="theText"></p>
<p id="theNumber"></p>
a charachter: <input type="charachter" id="theChar">
a number: <input type="number" id="theNbr">
<button onclick="printOut()">print out!</button>
<script type="text/javascript" src="script.js" ></script>
</body>
</html>
Code in Javascript:
function printOut(){
var theText = document.getElementById("theText").innerHTML;
document.getElementById("theText").innerHTML=
document.getElementById("theChar").value;
var theNumber = document.getElementById("theNbr").innerHTML;
document.getElementById("theNumber").innerHTML=
document.getElementById("theNbr").value;
var newText= theText;
var outPut;
for(i = 0; i<theNumber; i++){
newText =newText + theText;
}
newText = newText + "<br>";
for( i = 0; i< theNumber; i++){
outPut = outPut + newText;
}
document.getElementById("theText").innerHTML= outPut;
}
There are several issues in your code, even after the corrections you made after comments were made. Some of the more important:
Don't use innerHTML on an input element. It makes no sense. To get its value, use value.
Don't assign to document.getElementById("theNumber").innerHTML: it will replace any HTML you already had, and thus will remove the theNbr input. Any reference to it will fail with an error from now on.
Initialise your variables before reading from them. outPut is never initialised and so outPut + newText will give undesired results.
Although your can do this with for loops, there is a nice string method in JavaScript with which you can repeat a character or even a longer string: repeat.
Here is how it could work:
function printOut(){
var theNumber = document.getElementById("theNbr").value; // Don't use innerHTML
var theChar = document.getElementById("theChar").value;
var oneLine = theChar.repeat(theNumber) + "<br>";
var output = oneLine.repeat(theNumber);
document.getElementById("theText").innerHTML = output;
}
a charachter: <input type="charachter" id="theChar">
a number: <input type="number" id="theNbr">
<button onclick="printOut()">print out!</button>
<p id="theText"></p>
I'm trying to build a function, that receives a string with this format:
"hello wor**"
The * could be anywhere on the string.
It should return:
<span>hello wor</span><input type='text'></input>
So the string could be "hel** wor*d" also
and the return should be:
<span>hel</span><input type='text'> <span>wor</span><input type='text'><span>d</span>
I could do it easily with a loop on each char, but I'm looking for more elegant solutions.
I think that it could be solved with a regex, and using replace I got the "*" covered:
var text = "hello wor**";
text.replace(/\*+/g, "<input type='text'></input>");
I have not yet found a way of capturing the remaining text to render the
<span>
You're not using the result of the replace function. Try this:
var text = "*hel** wor*d*";
var element = text.split(/\s*\*+\s*/g);
element = "<span>"+ element.join("</span><input type='text'><span>") + "</span>";
element = element.replace(/<span><\/span>/g, "");
console.log(element);
'hello wor**'.replace(/\*+/g, "<input type='text'></input>");
This returns hello wor. All you have to do is concatenate the string with the rest of the data you want, like so:
var text = "hello wor**";
text = '<span>' + text.replace(/\*+/g, '') + '</span><input type=\'text\'></input>';
<html>
<head>
</head>
<body>
<span id="hi">hello wor**</span>
</body>
</html>
i use jquery in this
$( document ).ready(function() {
var texty = $('#hi').text();
$('#hi').replaceWith(texty.replace(/\*+/g, "<input type='text'></input>"))
});
I am trying to write a quick program that counts the number of words in AngularJS. Basically a textarea in HTML and underneath it should display the number of words as the user inputs them.
So this is my HTML code:
<!doctype html>
<html ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"></script>
<script src="wordcount.js"></script>
</head>
<body>
<div ng-controller="wordCount">
<label>Copy and Paste your text:</label><br>
<textarea cols="80" rows="20" ng-model="mytext"></textarea>
<hr>
<span>{{wordCount()}} word(s)</span>
</div>
</body>
</html>
And here is my Javascript file called wordcount.js (to count the number of words in a given string):
function wordCount($scope) {
$scope.numberofwords = function(s) {
s = document.getElementById("mytext").value;
s = s.replace(/(^\s*)|(\s*$)/gi,"");
s = s.replace(/[ ]{2,}/gi," ");
s = s.replace(/\n /,"\n");
return s.split(' ').length;
}
}
I basically found the above on http://www.mediacollege.com/internet/javascript/text/count-words.html
So I have probably not fully understood how to use AngularJS (and the JS code is probably wrong too) to update the number of words instantly. Right now it doesn't show anything but "words".
Does anyone have an idea?
One of correct way is to use a $scope function:
<body ng-controller="WCController">
<h3>World count</h3>
<div>total words: <span ng-bind="countOf(myText)"></span></div>
<textarea ng-model="myText"></textarea>
</body>
and at the controller:
$scope.countOf = function(text) {
var s = text ? text.split(/\s+/) : 0; // it splits the text on space/tab/enter
return s ? s.length : '';
};
You can test this on plunker:
http://run.plnkr.co/Mk9BjXIUbs8hGoGm/
Solution
update a wordCount property when myText changes.
use simple regexp in a String.prototype.match call.
use this updated wordCount scope property in your template.
Code
Your watcher should look like something like that:
$scope.$watch('myText', function(text) {
// no text, no count
if(!text) {
$scope.wordCount = 0;
}
// search for matches and count them
else {
var matches = text.match(/[^\s\n\r]+/g);
$scope.wordCount = matches ? matches.length : 0;
}
});
Important note
Why computing the count in a watcher ?
To prevent this count from being computed on each digestion, the way it is when you use such a wordCount() method call in your template !