I am working on a simple project that generates Facebook BBCode (or something like that) in images that you can use while chatting.
Here's my full code:
<html>
<head>
</head>
<body>
<script type="text/javascript">
function gear()
{
var textArea = document.getElementById("id");
var insertedText = theForm.theText.value;
var charChanger = insertedText.replace(/a/ig, "[[f9.cha]] ").replace(/b/gi, "[[f9.chb]] ").replace(/c/gi, "[[f9.chc]] ").replace(/d/gi, "[[f9.chd]] ").replace(/e/gi, "[[f9.che]] ").replace(/f/gi, "[[f9.chf]] ").replace(/g/gi, "[[f9.chg]] ").replace(/h/gi, "[[f9.chh]] ").replace(/i/gi, "[[f9.chi]] ").replace(/j/gi, "[[f9.chj]] ").replace(/k/gi, "[[f9.chk]] ").replace(/l/gi, "[[f9.chl]] ").replace(/m/gi, "[[f9.chm]] ").replace(/n/gi, "[[f9.chn]] ").replace(/o/gi, "[[f9.cho]] ").replace(/p/gi, "[[f9.chp]] ").replace(/q/gi, "[[f9.chq]] ").replace(/r/gi, "[[f9.chr]] ").replace(/s/gi, "[[f9.chs]] ").replace(/t/gi, "[[f9.cht]] ").replace(/u/gi, "[[f9.chu]] ").replace(/v/gi, "[[f9.chv]] ").replace(/w/gi, "[[f9.chw]] ").replace(/x/gi, "[[f9.chx]] ").replace(/y/gi, "[[f9.chy]] ").replace(/z/gi, "[[f9.chz]] ");
textArea.innerHTML = charChanger;
}
</script>
<div align="center"><form name="theForm">
<textarea rows="5" name="theText" cols="120" onkeyup="gear();"></textarea>
<br>
<textarea readonly id="id" rows="20" cols="120"></textarea>
</form></div>
</body>
</html>
There are two <textarea>s. The first one is filled with strings, and the second replaces the strings by their replacement values.
And the function starts working after keyup event. It should work perfectly, but it returns some weird replacements starting from a character to g (the rest is working).
So is there a fix? Or another way, like replacing using arrays?
You don't need 100 replacements, just one will do.
insertedText.replace(/([a-z])/gi, '[[f9.ch$1]]')
http://jsfiddle.net/PRYWm/1/
Related
Good morning to all
I have a question related to my big commerce products title. here I need the first part of the product's title in bold and after the hyphen or dash the second part need in italic. But problem is that the products title comes with one global variable %%GLOBAL_ProductName%% which I cannot make separated with the span tag. so can you suggest me how I can achieve the rest of strings after hyphen show in Italics with the help of javascript?
For example, check this screenshot https://www.screencast.com/t/fKy0FhByzzl
and here is big commerce website http://rp-staging2.mybigcommerce.com/categories
<li class="%%GLOBAL_AlternateClass%%">
<div class="ProductImage" data-product="%%GLOBAL_ProductId%%">
%%GLOBAL_ProductThumb%%
</div>
<div class="OutOfStockMessage InfoMessage" style="%%GLOBAL_ItemSoldOut%%">
%%SNIPPET_SideAddItemSoldOut%%
</div>
<div class="ProductActionAdd" onclick="location.href='%%GLOBAL_ProductLink%%';">
<p>%%GLOBAL_ProductName%%
</p>
<p><em class="p-price">%%GLOBAL_ProductPrice%% USD</em>
</p>
%%GLOBAL_ProductAddText%%
</div>
</li>
%%GLOBAL_ProductName%%
this variable showing products name please check screenshot and website i have provided link
Using some of the cool es6 features (array destructuring and template literals)
$(".pname").each(function () {
[beforeDash, afterDash] = $(this).text().split(" - ");
$(this).html(`${beforeDash} - <i>${afterDash}</i>`);
});
Looks like:
And if you are using jQuery in your website, you can use something like this:
$( window ).on( "load", function(){
var text = $('.text');
var x = text.text().split('-');
text.html(`${x[0]} - <i>${x[1]}<i>`);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="text">
Hello - World
</div>
When ever possible do this kind of split at the server side. Because client side you will manipulate strings after loading the page. So it is not good to do at client side. But anyhow I have written jquery code to fulfill your requirement. I have written in a click event for demo purpose. Please do the logic on onload event.
$("#btn").click(function(){
$(".productName").each(function(){
var title = $(this).text();
var firstSentence = "<b>"+title.substr(0,title.indexOf('-'))+"</b>";
var secondSentence = "<i>"+title.substr(title.indexOf('-')+1)+"</i>";
var finalTitle = firstSentence+ "-" + secondSentence;
$(this).html(finalTitle);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<a class="productName"> Sample1 - Product Name1</a><br>
<a class="productName"> Sample2 - Product Name2</a><br>
<input id="btn" type="button" value="Change Format">
</body>
</html>
Check this if it helps...
https://jsfiddle.net/Lz8p11mc/1/
You need to split your product name with '-' and then add these isolated names in separate spans and then you can style these spans as you want. I have written code for simple test case , you can modify it as per your requirement.
<html>
<script>
var productName = 'ABC-XYZ';
var separatedNames = productName.split('-');
var firtsName = separatedNames[0];
var secondname = separatedNames[1];
window.onload = function() {
//when the document is finished loading, replace everything
//between the <a ...> </a> tags with the value of splitText
document.getElementById("myTag").innerHTML = '<span>'+firtsName+'</span>-<span class="secondnameCls">'+secondname+'</span>';
}
</script>
<body>
<li class="%%GLOBAL_AlternateClass%%">
<p><a id='myTag'></a></p>
</li>
</body>
</html>
I'm trying to make a simple multi-search tool for learning German. When I put in certain characters, they change. For example, ü is %FC, ä is %E4, ö is $F6, ß is %DF. I assume somewhere the characters are being converted to some other character set other than Unicode
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script language="javascript" charset="UTF-8">
function basicSearch()
{
//document.basicForm.basicWord.value = '\u1495';
var basicSubmit=document.basicForm;
var basicWord = escape(basicSubmit.basicWord.value);
document.getElementById("demo").innerHTML = basicWord;
window.open("https://translate.google.com/#de/en/" + basicWord);
return false;
}
</script>
</head>
<body>
<form name="basicForm" onSubmit="return basicSearch();" accept-charset="UTF-8">
<input type="text" name="basicWord">
<input type="submit" name="SearchSubmit" value="Search">
</form><br>
<p id="demo"></p>
</body>
</html>
Its a good idea to consider http encoding any URIs you are manually constructing. In this case we can use encodeURIComponent on the text of the input to properly http encode data passed in the URI.
// früh -> early
var basicWord = encodeURIComponent(basicSubmit.basicWord.value);
// basicWord = 'fr%C3%BCh';
Other cases might warrant using encodeURI. See this question for more info.
var basicWord = escape(basicSubmit.basicWord.value);
JavaScript's escape()/unescape() encoding is a bizarre custom format you almost never want to use. For encoding URL parameters using the actual real URL rules, the function you want instead is encodeURIComponent().
document.getElementById("demo").innerHTML = basicWord;
Avoid writing HTML markup to the document, you get HTML-injection problems which can lead to cross-site scripting security holes. Write to textContent instead to write normal text.
window.open("https://translate.google.com/#de/en/" + basicWord);
(Incidentally Google Translate also accepts form parameters: q for text to translate, sl for source and tl for target language. So FWIW you could do this with a simple form without JS.)
Thank you both. If anyone is interested, below is the final coding. I made it to help create flash cards for ANKI using Gabriel Wyner's youtube vids and his multi-tool.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Page Title</title>
</head>
<body>
<script>
function basicSearch() {
var basicSubmit=document.basicForm;
var basicWord = encodeURIComponent(basicSubmit.searchterms.value);
window.open("https://de.wiktionary.org/w/index.php?search=" + basicWord + "&title=Spezial:Suche&go=Seite&searchToken=480i5tddc2tqpr6njyi8gx2oa");
window.open("http://forvo.com/search/" + basicWord + "/");
window.open("https://www.google.de/search?q=" + basicWord + "&biw=1280&bih=611&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiOydnfssfRAhVCqlQKHaPSDvoQ_AUIBigB#q=" + basicWord + "&tbm=isch&tbs=isz:m");
window.open("https://translate.google.com/#de/en/" + basicWord);
return false;
}
function actionSearch() {
var actionSubmit=document.actionForm;
var actionWord = encodeURIComponent(actionSubmit.searchterms.value);
window.open("https://www.google.de/search?q=" + actionWord + "&biw=1280&bih=611&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiiwtDttMfRAhVkx1QKHc6PCgMQ_AUIBigB#tbs=isz:m%2Citp:animated&tbm=isch&q=" + actionWord);
return false;
}
</script>
<form name="basicForm" onSubmit="return basicSearch();">
Search for a basic word:
<input type="text" name="searchterms">
<input type="submit" name="SearchSubmit" value="Search">
</form><br>
<form name="actionForm" onSubmit="return actionSearch();">
Search google for animation:
<input type="text" name="searchterms">
<input type="submit" name="SearchSubmit" value="Search">
</form><br>
German quotes/sayings
<h2>English links for gifs: (for verbs or other)</h2>
http://giphy.com/<br>
http://www.reactiongifs.com/<br>
https://www.reddit.com/r/gifs/<br>
https://www.reddit.com/r/reactiongifs/<br>
https://www.reddit.com/r/analogygifs<br>
https://www.reddit.com/r/HighQualityGifs/<br>
https://www.reddit.com/r/DANCEGIFS/<br>
http://www.gifbin.com/<br>
</body>
</html>
I have a very basic input/output structure in HTML:
<textarea id="input" onkeyup="sendCode()">
Hello World!
</textarea>
<div id="output"></div>
And I have JS function that should pass everything from input to output:
var input = document.getElementById("input");
var output = document.getElementById("output");
function sendCode(){
output.innerHTML = input.innerHTML;
}
The sendCode() function works when I call it manually, but it seems that onkeyup event not firing in this textarea.
Here is jsfiddle: http://jsfiddle.net/mudroljub/y5a2n8ab/
Any help?
UPDATE: jsfiddle is updated and working now.
Use value since it's not a content text but a value property
var input = document.getElementById("input");
var output = document.getElementById("output");
function sendCode(){
output.innerHTML = input.value;
}
And a working demo here
I would first like to point out that this will not run because the code runs before the HTML exists, so first off, put these lines inside a function:
window.onload= function anyname() {
var input = document.getElementById("input");
var output = document.getElementById("output");
}
Secondly, try using either:
editor.onkeyup = "sendCode()"
in your script area or at the top of the new function i created:
editor.addEventListener(keyup,sendCode,false)
Basically when a key goes up in that area it calls the sendCode() function. The false is if you don't want to use capture which I think is default anyway but just to be safe.
Basically java script is not that dynamic.So a better option is to
use jQuery.
[Note:- "jquery-2.2.2.min.js" given in src, in script tag,
is Jquery Library file codes can be copied from following link :http://code.jquery.com/jquery-2.2.2.min.js]
Just copy the contents from above link,into a textfile , save it by the name "jquery-2.2.2.min.js"
or any other name as you wish.The src of script should contain the same.
The "jquery-2.2.2.min.js" should be in the same directory where
you have the html file. Otherwise full path to be mentioned.
Here is the answer to your question.
<html>
<head>
<title>Dynamic TextArea</title>
<script type="text/javascript" src="jquery-2.2.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("textarea").keyup(function(){
sendCode();
});
});
function sendCode(){
document.getElementById("output").innerHTML =
document.getElementById("input").value;
}
</script>
</head>
<body>
<form>
<textarea id="input">
Hello World!
</textarea>
</form>
<span id="output"></span>
</body>
</html>
If you have any doubts please ask.
I am sure once you learn to use jQuery you would forget javascript.
Where do you define the sendCode() function? It might not exist at the point where you create your text area.
This snippet should work:
<textarea id="editor">
Hello World!
</textarea>
<div id="output"></div>
<script type="text/javascript">
var editor = document.getElementById("editor");
var output = document.getElementById("output");
function sendCode(){
output.innerHTML = editor.value;
}
editor.addEventListener('keyup',sendCode);
</script>
I write this script to change the value of a textarea but I fail to do so. What's wrong with my code?
<html>
<head>
<script type="text/javascript">
document.getElementsByName("status").innerHTML = "hi";
document.getElementsByName("status").title= "hi";
document.getElementsByName("status").placeholder= "hi";
</script>
</head>
<body>
<textarea placeholder="What's on your mind?" onfocus="window.UIComposer && UIComposer.focusInstance("c4d981e9a2c98b0483252333");" name="status" id="c4d981e9a2c98b0483252333_input" title="What's on your mind?" class="DOMControl_placeholder UIComposer_TextArea">What's on your mind?</textarea>
</body>
</html>
Iif you try using:
var textarea = document.getElementById('c4d981e9a2c98b0483252333_input');
textarea.value = 'hi';
It should work.
Otherwise, because of the way getElementsByName works, you'd need to provide an index (zero-based) to the call to identify which of the textareas you want to work with:
var textarea = document.getElementByName('status')[0]; // selects the first element of name 'status'
textarea.value = 'hi';
Two problems
First, document.getElementsByName returns a NodeList (which is like an array), not a single element.
Second, you do nothing to delay the execution of the JS until the element actually exists. So it won't find it anyway.
Change to document.getElementsByName("status")[0]
Move the <script> element so it appears after the textarea.
I wouldn't be comfortable with using innerHTML to modify a form control either. I'd switch to value instead.
<script type="text/javascript">
document.getElementsByName("status")[0].value = "hi";
</script>
put this script in the body
<script type="text/javascript">
document.getElementById("status").value= "hi";
</script>
change getElementsByName to getElementById
getElementsByName -> returns array of elements
getElementById -> returns single control..
then put the script in between body tags not in header.....
<html>
<head>
</head>
<body>
<textarea placeholder="What's on your mind?" onfocus="window.UIComposer && UIComposer.focusInstance("c4d981e9a2c98b0483252333");" name="status" id="c4d981e9a2c98b0483252333_input" title="What's on your mind?" class="DOMControl_placeholder UIComposer_TextArea">What's on your mind?</textarea>
<script type="text/javascript">
document.getElementById("c4d981e9a2c98b0483252333_input").value = "hi";
document.getElementsByName("status")[0].value = "hi";
</script>
</body>
</html>
Is there a way in JavaScript or MooTools to retrieve the actual text in the value from an input element without the browser interpreting any html special entites? Please see the example included below. My desired outcome is:
<div id="output">
<p>Your text is: <b>[<script>alert('scrubbed');</script>]</b></p>
</div>
Note that it works if I type/copy <script>alert('scrubbed');</script> directly into the text input box, but fails if I insert right after loading the page.
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>scrubtest</title>
</head>
<body id="scrubtest" onload="">
<script type="text/javascript" language="JavaScript" src="/js/mootools-core.js"></script>
<input type="text" name="scrubtext" value="<script>alert('scrubbed');</script>" id="scrubtext"/><br />
<input type="button" value="Insert" onclick="insertText();"/><br />
<input type="button" value="Get via MooTools" onclick="alert($('scrubtext').get('value'));"/><br />
<input type="button" value="Get via JavaScript" onclick="alert(document.getElementById('scrubtext').value);"/><br />
<div id="output">
</div>
<script type="text/javascript" charset="utf-8">
function insertText()
{
var stext = $('scrubtext').get('value');
var result = new Element( 'p', {html: "Your text is: <b>["+stext+"]</b>"} );
result.inject($('output'));
}
</script>
</body>
</html>
{html: "Your text is: <b>["+stext+"]</b>"}
That's your problem: you're taking a plain text string and adding it into HTML markup. Naturally any < characters in the text string will become markup, and you give yourself a potential client-side cross-site-scripting vulnerability.
You can HTML-escape, but there's no built-in function to do it in JS, so you have to define it yourself, eg.:
// HTML-encode a string for use in text content or an attribute value delimited by
// double-quotes
//
function HTMLEncode(s) {
return s.replace(/&/g, '&').replace(/</g, '<').replace(/"/g, '"');
}
...
var result = new Element('p', {html: "Your text is: <b>["+HTMLEncode(stext)+"]</b>"});
However, it is generally simpler to use DOM methods to add plain text without the bother of string hacking. I believe Moo would do it like this:
var bold= new Element('b', {text: stext});
var result= new Element('p', {text: 'Your text is: '});
bold.inject(result);
escape & like this: &
<input type="text" name="scrubtext" value="<script>alert('scrubbed');</script>" id="scrubtext"/>
You can change the & characters into & by using
var result = new Element( 'p', {html: "Your text is: <b>["+stext.replace(/&/g,'&')+"]</b>"} );
Addition: I would go with bobince on the benefit of using the DOM node properties, instead of injecting arbitrary HTML.
function htmlspecialchars_decode(text)
{
var stub_object = new Element('span',{ 'html':text });
var ret_val = stub_object.get('text');
delete stub_object;
return ret_val;
}