I'm trying to write something like an image font generator, but I can not check if the form value is an space, or give an URL to an whitespace image.
Here is my code:
<html><head><title>untitled</title>
<script type="text/javascript">
<!--
function fontgen(text) {
var url = './fonts/';
var letters = text.split('');
var imgStr = "";
for (var i in letters) {
imgStr += '<img src="' +url+letters[i]+ '.gif">';
}
document.getElementById('name').innerHTML = imgStr;
return false;
}
//-->
</script>
</head>
<body>
<form name="myform" action="">
<input type="text" name="myinput" size="20"><br>
<input type="button" value="Make Font" onclick="return fontgen(document.myform.myinput.value)">
</form>
<div id="name"></div>
</body>
</html>
function fontgen(text) {
var url = './fonts/',
letters = text.split(''),
imgStr = "";
// First, you need a valid for loop:
for (var i = 0; i < letters.length; i++) {
if (letters[i] !== ' ') { // then, check to see if it is a space
imgStr += '<img src="' +url+letters[i]+ '.gif">';
}
}
document.getElementById('name').innerHTML = imgStr;
return false;
}
From what I can tell from your question, you're looking for something like this:
for (var i=0;i<text.length;i++)
{
if (text.charAt(i) !== ' ')
{//using charAt, you're supporting all browsers, without having to split the string
console.log(text.charAt(i) + ' is not space');
}
}
But an easier way of doing this, without having to loop through all chars, 1 by 1, is this:
if (text.indexOf(' ') === -1)
{
console.log('No spaces in ' + text + ' found');
}
Or, if you want to, you can replace or remove all spaces in one go:
text = text.replace(/\s/g,'_');//replaces spaces with underscores
text = text.replace(/\s/g, '');//removes spaces
Regex-mania way. Suppose you have a certain set of chars as gifs, you can easily use a single regex to replace all of those chars with their corresponding images in one fell swoop:
var imgString = text.replace(/([a-z0-9\s])/gi, function(char)
{
if (char === ' ')
{
char = 'space';//name of space img
}
return '<img src="'url + char + '.gif"/>';
});
Same logic applies to chars like ! or ., since they're not exactly suitable for file names, use an object, array or switch to replace them with their corresponding file-names.Anyway, with input like foo bar, the output of the code above should look something like this:
<img src="./fonts/f.gif"/><img src="./fonts/o.gif"/><img src="./fonts/o.gif"/><img src="./fonts/space.gif"/><img src="./fonts/b.gif"/><img src="./fonts/a.gif"/><img src="./fonts/r.gif"/>
Not sure why your path is ./foo/[].gif, I suspect foo/[].gif would do just as well, but that's not the issue at hand here.
In case you're interested: here's some more about replacing using regex's and callbacks
try replacing letters[i]
with:
(letters[i] == " ") ? "spacefilename" : letters[i]
this is a ternary operator. basically a shorthand if statement that can be used directly in place of letters[i]
in a sense it would be like replacing letters[i] with myfilename(letters[i])
where the myfilename function is
function myfilename(char)
{
if (char == " ") {
return "space";
} else {
return char;
}
}
so your code would look like this:
<html><head><title>untitled</title>
<script type="text/javascript">
<!--
function fontgen(text) {
var url = './fonts/';
var letters = text.split('');
var imgStr = "";
for (var i = 0; i < letters.length; i++) {
imgStr += '<img src="' +url+(letters[i] == " ") ? "spacefilename" : letters[i]+ '.gif">';
}
document.getElementById('name').innerHTML = imgStr;
return false;
}
//-->
</script>
</head>
<body>
<form name="myform" action="">
<input type="text" name="myinput" size="20"><br>
<input type="button" value="Make Font" onclick="return fontgen(document.myform.myinput.value)">
</form>
<div id="name"></div>
</body>
</html>
/e also as someone else mentioned, the for loop is wrong. i corrected that just now.
a "for...in" loop could work there... don't want to get into all that though.
Try changing the character into a char code and having a corresponding image file for each code you want to support; you can also put a range check via if statement to make sure the codes fall within your accepted ranges.
function fontgen(text)
{
var imgStr = "";
for (var i = 0; i < text.length; i++)
imgStr += '<img src="./fonts/' + text[i].charCodeAt(0) + '.gif">';
document.getElementById('name').innerHTML = imgStr;
return false;
}
If you supply this function the phrase "this is a test" it will result in:
<div id="name">
<img src="./fonts/116.gif">
<img src="./fonts/104.gif">
<img src="./fonts/105.gif">
<img src="./fonts/115.gif">
<img src="./fonts/32.gif">
<img src="./fonts/105.gif">
<img src="./fonts/115.gif">
<img src="./fonts/32.gif">
<img src="./fonts/97.gif">
<img src="./fonts/32.gif">
<img src="./fonts/116.gif">
<img src="./fonts/101.gif">
<img src="./fonts/115.gif">
<img src="./fonts/116.gif">
</div>
<img src="./fonts/32.gif"> would be the space image.
Related
i am new in javascript.
I have below code where textarea contains text as...
<textarea id="myBox" >
{Picker:} Helper
This is just demo...
</textarea>
<br/>
<span id="ans"></span> <br/>
<input type="button" onclick="getWord()" value="Click"/>
i am trying to find out the word exact after the {Picker:}, i.e. i want to find word "Helper". So word {Picker:} is the point from where i am starting to find immediate word after it. For this i using indexOf. What i did uptil now is ...
<script>
function getWord() {
var val = $("#myBox").val();
var myString = val.substr((val.indexOf("{Picker:}")) + parseInt(10), parseInt(val.indexOf(' ')) );
$("#ans").text(myString);
}
</script>
will anyone guide me to find what mistake i am making. Thanks in advance.
You should start from the index of "{Picker:}" + 9, because the length of the particular string is 9.
Parse till the the index of '\n' which is the line break character.
String.prototype.substr() is deprecated, use String.prototype.substring() instead.
function getWord() {
var val = $("#myBox").val();
var myString = val.substring((val.indexOf("{Picker:}")) + 9, val.indexOf('\n'));
$("#ans").text(myString);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<textarea id="myBox">
{Picker:} Helper
This is just demo...
</textarea>
<br />
<span id="ans"></span> <br />
<input type="button" onclick="getWord()" value="Click" />
var val = $("#myBox").val();
console.log(val)
var tempArray = val.replace("\n", " ").split(" ");
var wordToFind;
for(var i = 0 ; i < tempArray.length; i++) {
var word = tempArray[i];
if (word == "{Picker:}") {
wordToFind = tempArray[i + 1]
}
}
console.log(wordToFind)
This will assign what ever word comes after Picker: to the wordToFind variable.
Check working :https://jsfiddle.net/o5qasnd0/14/
You could do something like this
const text = "{Picker:} Helper";
const wordArr = text.split(' ');
const idx = wordArr.indexOf('{Picker:}');
console.log(idx != -1 && (idx + 1) < wordArr.length ? wordArr[idx + 1] : 'not found');
I am trying to make a blog type of website. I got to a point where you can enter text into a textarea box and then click submit to have it appear below. However, I have come to a problem where it does not save the format of the input (notably for me, transforms paragraphs into spaces). I have read that this would require a rich-text editor, and I have tried TinyMCE but it gives a lot more options than needed or which would be able to be used in my case. Is there a simple way to fix this problem? If not, what is the best way to go about this?
I am mainly after the paragraph, tab, and multiple spaces formatting, everything else is currently not needed.
Here is what I currently have that is related:
HTML
<!-- Blog Section -->
<div class="itemBlog">
<h2 id="itemBlogTitle">My Blog</h2>
<textarea type="text" rows="10" cols="100" class="blogTextArea" id="blogInput"></textarea>
<div onclick="newBlog()" class="addBtn">Add</div>
<ul id="blogList"></ul>
</div>
<script src="itemblog.js"></script>
JavaScript
// Create a new blog item when clicking on the "Add" button
function newBlog() {
var li = document.createElement("li");
var inputValue = document.getElementById("blogInput").value;
var t = document.createTextNode(inputValue);
li.appendChild(t);
if (inputValue != '') {
document.getElementById("blogList").appendChild(li);
}
document.getElementById("blogInput").value = "";
var textarea = document.createElement("TEXTAREA");
var txt = document.createTextNode("\u00D7");
textarea.className = "close";
textarea.appendChild(txt);
li.appendChild(textarea);
for (i = 0; i < close.length; i++) {
close[i].onclick = function () {
var div = this.parentElement;
div.style.display = "none";
}
}
}
EDIT: white-space: pre-wrap; fixed it, thank you
If you want something simple, just save into your database the input content with id description, after that it will respect the paragraph and spaces.
JQUERY
$('#test').keyup(function() {
var text = $(this).val();
var description = text.replace(/ /g, ' ').replace(/[\n]/g, '<br>');
$('#text').html(description)
$('#description').val(description)
});
<textarea id="test" cols="30" rows="10"></textarea>
<input id="description" name="description" hidden>
<div id="text"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
js
function formatString(el) {
var str = el.value;
str = str.replace(/ /g, ' ').replace(/[\n]/g, '<br>');
document.getElementById('text').innerHTML = str;
document.getElementById('description').value = str;
}
<textarea onkeyup="formatString(this)" cols="30" rows="10"></textarea>
<input id="description" name="description" hidden>
<div id="text"></div>
You can create a function nl2br() as folows:
function nl2br (str, is_xhtml) {
if (typeof str === 'undefined' || str === null) {
return '';
}
var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
}
You can see more here
I'm doing this for a school project but one thing is bugging me, there is a part of the project that requires me to change white space or just " " a space to a number. Here is my code:
I know its messy, I've only been coding for half a year
exclsp is "exclude spaces"
inclsp is "include spaces"
dispwos is "display without spaces"
dispwsp is "display with spaces"
var txt;
var num;
var spce = 0;
function cnt()
{
txt = document.getElementById('disp').value;
num = txt.length;
// includes spaces into the returned number
if (document.getElementById("inclsp").checked == true)
{
document.getElementById("dispwsp").innerHTML = num + " characters.";
}
// excludes spaces from the returned number
if (document.getElementById("exclsp").checked === true)
{
for (var i = 0; i < num; i++) {
if (txt.includes(" "))
{
// alert("THERES A SPACE HERE");
spce++;
}
else
{
num = num;
}
}
}
document.getElementById("dispwos").innerHTML = num - spce + " characters.";
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="LetterCount.js"></script>
<link rel="stylesheet" type="text/css" href="LetterCount.css"/>
<title>Letter Counter</title>
</head>
<body>
<textarea rows="4" cols="50" placeholder="Input your text here!" id="disp"></textarea><br>
<form name="form1">
<input type="radio" name="button" id="inclsp"> Include spaces</input><br>
<input type="radio" name="button" id="exclsp"> Exclude spaces</input><br>
</form>
<button onclick="cnt()">Click Me!</button><br><br>
<div id="dispwsp"></div>
<div id="dispwos"></div>
</body>
</html>
I think you need to change this line:
if (txt.includes(" "))
to
if (txt[i] == " ")
so that you're actually checking each character rather that attempting to examine the whole string each time.
You could also use a regular expression and do it in one simple line of code and eliminate the loop altogether:
spce = txt.match(/\s/g).length
I don't understand the purpose of the dispwsp dispwos so I just removed them. You only have 1 result you want to display so why put it in different places just make one div for your result, like
<div id="result"></div>
And your JS can be simplified a lot, you don't need to loop through the letters. Here's the fiddle: https://jsfiddle.net/zwzqmd27/
function cnt() {
var inputText = document.getElementById("disp").value;
if (document.getElementById("exclsp").checked) //exclude spaces
{
document.getElementById("result").innerHTML = inputText.split(" ").join("").length + " characters";
}
else //include spaces
{
document.getElementById("result").innerHTML = inputText.length + " characters";
}
}
Possible duplicate of Check if a string has white space
But you can try this.
function hasWhiteSpace(s) {
return s.indexOf(' ') >= 0;
}
If You want to change a white space in a string to a number..
This could possibly help you ...
str.replace(/\s/g,"9");//any number(that You want)
This piece of code is basically replaces the white space with a number..
As #Micheal said, you can use indexOf() method to check if particular character(s) is present in your text content.
You just need to pass the character or substring(set of characters) to check if it is present.
Example :
var myText = "Sample text";
var substringIndex = myText.indexof(" "); //substringIndex = 6
substringIndex = mytext.indexof("ex");//substringIndex = 8;
substringIndex = mytext.indexof("tt"); // substringIndex =-1;
If substring doesn't matches, it will return -1 as index.
By using index you can say, if particular character(substring) presents if index value is greater than -1.
Note : If u pass set of characters, it will return only the starting index of the first character if entire set matches.
In your case, it would be like
...........
...........
if (txt.indexOf(" ")>-1)
{
// alert("THERES A SPACE HERE");
spce++;
}
else
{
num = num;
}
...............
...............
Just replace script with code bellow..
I do it for you...
var txt;
var num;
var spce = 0;
function cnt()
{
//to clear "dispwsp" and "dispwos" before action in cnt() function
document.getElementById("dispwsp").innerHTML = "";
document.getElementById("dispwos").innerHTML = "";
txt = document.getElementById('disp').value;
num = txt.length;
// includes spaces into the returned number
if (document.getElementById("inclsp").checked == true)
{
document.getElementById("dispwsp").innerHTML = num + " characters.";
}
// excludes spaces from the returned number
if (document.getElementById("exclsp").checked == true)
{
num = 0;
spce = 0;
for (var i = 0; i < txt.length; i++) {
var temp = txt.substring(i, (i+1));
if(temp==" ")
{
spce++;
}else
{
num++;
}
document.getElementById("dispwos").innerHTML = num + " characters and "+ spce +" spces ";
}
}
}
I want to insert an ending slash before the closing bracket of every img tag found in a string.
This (modified from here) is correctly returning the position of each instance of img:
var re = /img\s/g,
match;
while (match = re.exec(str)) {
console.log(match.index); //
}
Knowing this, how can I find the next > after each imgand insert a / before it?
How about this, it's simple but seems like it would work for your case:
str.replace(/(<img[^>]*)>/g, "$1 />");
if you wanted it to be a little more smart, you could do something like this:
str.replace(/(<img[^>]*?) *\/?>/g, "$1 />");
this would account for things that already have a space and/or a slash at the end... and create the same output for all of the following:
IN:
<img src='foo.png'>
<img src='foo.png' >
<img src='foo.png'/>
<img src='foo.png' />
OUT for all the above:
<img src='foo.png' />
if you would rather have <img src='foo.png'/>, just remove the space after $1 in the replace.
try something like this:
var imgs = "<img blblblb > <img adadasd>"
var pattern = /(<img[^>]*)>/g;
imgs = imgs.replace(pattern, "$1/>");
console.log(imgs);
//<img blblblb /> <img adadasd/>
I have a non-regex solution, if you’re interested:
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=ISO-8859-1"/>
<script type="text/javascript">
function close_img_tags(){
var str = document.getElementById("txt").value, len = str.length, i, j;
for(i = 0; i < len-4; i++){
if(str[i]+str[i+1]+str[i+2]+str[i+3] == "<img"){
for(j = i+4; j < len; j++){
if(str[j] == ">"){
if(str[j-1] != "/"){
str = str.substr(0, j)+"/"+str.substr(j);
i = j+2;
}
else{
i = j+1;
}
break;
}
}
}
}
document.getElementById("txt").value = str;
}
</script>
<style type="text/css">
textarea{
width:400px;
height:300px;
}
</style>
</head>
<body>
<textarea id="txt"></textarea><br/>
<button type="button" onclick="close_img_tags();">Edit HTML</button>
</body>
</html>
Demo: http://jsfiddle.net/eZu9U/
I tried using the following code to format a text field value from (N50,000.00 NGN) to (50000) but the result instead of producing 50000 is producing 5000000.
Can someone please help?
<script type="text/javascript" language="javascript">
function doWork() {
var amount = document.getElementsByName('amount');
var str = amount[0].value;
var temp = '';
for (i = 0; i < str.length; i++) {
if (!isNaN(str[i]))
temp += str[i];
}
amount[0].value = temp;
}
</script>
<input type="text" name="amount" value="N50,000.00 NGN" />
<input type="button" value="submit" onclick="doWork();">
The simplest method to get what you want might be to just add another condition in your for loop:
if (str[i] === '.')
break;
Let's take a look at the value you are trying to format.
In N50,000.00 NGN all digits are not NaN. So your result is 5000000 (50 000 00). The solution is to stop at dot symbol, e.g.
function doWork() {
var amount = document.getElementsByName('amount');
var str = amount[0].value;
var temp = '';
for (i = 0; i < str.length; i++) {
if (str[i] === '.') break; // there it is
if (!isNaN(str[i]))
temp += str[i];
}
amount[0].value = temp;
}
Here's one way to do it with a regex. Note, that if the user has multiple decimal points in the input field it may act oddly.
<script type="text/javascript" language="javascript">
function doWork() {
var amount = document.getElementsByName('amount');
amount[0].value = amount[0].value.replace(/[^0-9.]/g, "");
amount[0].value = amount[0].value.replace(/[.][0-9]*/g, "");
}
</script>
<input type="text" name="amount" value="N50,000.00 NGN" />
<input type="button" value="submit" onclick="doWork();">
The first line removes all characters except numbers and decimal points.
The second, removes all decimal points and any numbers to the right of them.
Using parseInt and toFixed may be better, though:
<script type="text/javascript" language="javascript">
function doWork() {
var amount = document.getElementsByName('amount');
amount[0].value = parseInt(amount[0].value.replace(/[^0-9.]/g, "")).toFixed(0);
}
</script>
<input type="text" name="amount" value="N50,000.00 NGN" />
<input type="button" value="submit" onclick="doWork();">
You're skipping over the decimal. Use:
if (!isNaN(str[i]) || str[i]=='.')