Converting HTML to its safe entities with Javascript - javascript

I'm trying to convert characters like < and > into < and > etc.
User input is taken from a text box, and then copied into a DIV called changer.
here's my code:
function updateChanger() {
var message = document.getElementById('like').value;
message = convertHTML(message);
document.getElementById('changer').innerHTML = message;
}
function convertHTML(input)
{
input = input.replace('<', '<');
input = input.replace('>', '>');
return input;
}
But it doesn't seem to replace >, only <. Also tried like this:
input = input.replace('<', '<').replace('>', '>');
But I get the same result.
Can anyone point out what I'm doing wrong here? Cheers.

A more robust way to do this is to create an HTML text node; that way all of the other potentially invalid content (there's more than just < and >) is converted. For example:
var message = document.getElementById('like').value;
document.getElementById('changer').appendChild(document.createTextNode(message));
UPDATE
You mentioned that your event was firing upon each key press. If that's what's triggering this code, you'll want to remove what was previously in the div before appending the text. An easy way to do that is like this:
var message = document.getElementById('like').value;
var changer = document.getElementById('changer');
changer.innerHTML = '';
changer.appendChild(document.createTextNode(message));

Try something like this:
function convertHTML(input)
{
input = input.replace(/>/g, '>');
input = input.replace(/</g, '<');
return input;
}
replace only replaces the first occurrence of > or < in the string, in order to replace all occurrences of < or >, use regular expressions with the g param to ensure the entire string is searched for all occurrences of the values.

Related

How to define a line break in extendscript for Adobe Indesign

I am using extendscript to build some invoices from downloaded plaintext emails (.txt)
At points in the file there are lines of text that look like "Order Number: 123456" and then the line ends. I have a script made from parts I found on this site that finds the end of "Order Number:" in order to get a starting position of a substring. I want to use where the return key was hit to go to the next line as the second index number to finish the substring. To do this, I have another piece of script from the helpful people of this site that makes an array out of the indexes of every instance of a character. I will then use whichever array object is a higher number than the first number for the substring.
It's a bit convoluted, but I'm not great with Javascript yet, and if there is an easier way, I don't know it.
What is the character I need to use to emulate a return key in a txt file in javascript for extendscript for indesign?
Thank you.
I have tried things like \n and \r\n and ^p both with and without quotes around them but none of those seem to show up in the array when I try them.
//Load Email as String
var b = new File("~/Desktop/Test/email.txt");
b.open('r');
var str = "";
while (!b.eof)
str += b.readln();
b.close();
var orderNumberLocation = str.search("Order Number: ") + 14;
var orderNumber = str.substring(orderNumberLocation, ARRAY NUMBER GOES HERE)
var loc = orderNumberLocation.lineNumber
function indexes(source, find) {
var result = [];
for (i = 0; i < source.length; ++i) {
// If you want to search case insensitive use
// if (source.substring(i, i + find.length).toLowerCase() == find) {
if (source.substring(i, i + find.length) == find) {
result.push(i);
}
}
alert(result)
}
indexes(str, NEW PARAGRAPH CHARACTER GOES HERE)
I want all my line breaks to show up as an array of indexes in the variable "result".
Edit: My method of importing stripped all line breaks from the document. Using the code below instead works better. Now \n works.
var file = File("~/Desktop/Test/email.txt", "utf-8");
file.open("r");
var str = file.read();
file.close();
You need to use Regular Expressions. Depending on the fields do you need to search, you'l need to tweek the regular expressions, but I can give you a point. If the fields on the email are separated by new lines, something like that will work:
var str; //your string
var fields = {}
var lookFor = /(Order Number:|Adress:).*?\n/g;
str.replace(lookFor, function(match){
var order = match.split(':');
var field = order[0].replace(/\s/g, '');//remove all spaces
var value = order[1];
fields[field]= value;
})
With (Order Number:|Adress:) you are looking for the fields, you can add more fields separated the by the or character | ,inside the parenthessis. The .*?\n operators matches any character till the first break line appears. The g flag indicates that you want to look for all matches. Then you call str.replace, beacause it allows you to perfom a single task on each match. So, if the separator of the field and the value is a colon ':', then you split the match into an array of two values: ['Order number', 12345], and then, store that matches into an object. That code wil produce:
fields = {
OrderNumber: 12345,
Adresss: "my fake adress 000"
}
Please try \n and \r
Example: indexes(str, "\r");
If i've understood well, wat you need is to str.split():
function indexes(source, find) {
var order;
var result = [];
var orders = source.split('\n'); //returns an array of strings: ["order: 12345", "order:54321", ...]
for (var i = 0, l = orders.length; i < l; i++)
{
order = orders[i];
if (order.match(/find/) != null){
result.push(i)
}
}
return result;
}

Javascript loop strings in between selected characters

I would like to know how to create a for-loop with text content that I cannot modify. The text I am given looks like so:
<start>John</stop><start>Billy</stop>
I have two texts, John and Billy that are each surrounded by start and stop tags. What I would like to do is add these names without the tags to my HTML. My incomplete code looks something like:
var mytext = "<start>John</stop><start>Billy</stop>";
var count = (mytext.match(/<start>/g) || []).length;
for (i = 0; i < count; i++){
something.innerHTML += eachname;
}
Would like to know how to complete this.
Try with /<[^>]*>/gi like the following:
Please Note: Since the output is plain text it is better to use textContent instead of innerHTML.
var mytext = "<start>John</stop><start>Billy</stop>";
function get_content() {
//var html = document.getElementById("txtInput").innerHTML;
document.getElementById("txt").textContent = mytext.replace(/<[^>]*>/gi, "");
}
get_content();
<div id="txt">
</div>
You can use the following javascript example for your solution.
var mytext = "<start>John</stop><start>Billy</stop>";
mytext = mytext.replace(/<\/?start[^>]*>/ig, ""); //Replace all <start> with blank
console.log(mytext.split(/<\/?stop[^>]*>/ig)); //Split by <stop> this may return an array ...

Guide on word occurrence in a textarea

I have a Textarea box, a textbox and a button. I would like on clicking the button, for the word in the textbox to be checked against words in the textarea and count number of occurrence.
I have tried last 2 days to write a click function to do this but not getting anywhere since not sure what codes or logic follows next. Only managed to read the contents in the textarea but not sure how to get the word in the textbox and search against sentence in textarea.
Please I am a newbie in JQuery so not asking for anyone to write the code but more of a guide if possible. If this question isn't permitted here, I am more than happy to delete it. Thanks
Use string.match() along with processing to ensure the first string is not empty and that there actually is a match. Did the following in jQuery since you seemed interested in using it.
var textVal = $('#textbox').val();
var textArea = $('#textarea').val();
var matching = new RegExp('\\b' + textVal + '\\b','g');
var count = textArea.match(matching);
var result = 0;
if (count !== null) {
result = count.length;
}
http://jsfiddle.net/promiseofcake/t8Lg9/3/
You are looking for string occurrences, so take a look at this thread.
You could do this using match(), as suggested in the comments:
var m = searchText.match(new RegExp(wordMatch.toString().replace(/(?=[.\\+*?[^\]$(){}\|])/g, "\\"), "ig"));
// m.length contains number of matches
But that will also match partial words, like 'fox' in 'foxy'. So another method is to split the input into words and walk over them one by one:
var count = 0;
var words = searchText.split(' ');
for (x in words) {
if (words[x].toLowerCase() == wordMatch) {
count++;
}
}
Take a look at this full example: http://jsfiddle.net/z7vzb/
<input type="text"/>
<textarea>...</textarea>
<button>Get</button>
<div></div>
<script>
$("button").click(function(){
count=$("textarea").text().split($("input[type=text]").val()).length-1;
$("div").html(count);
})
</script>

changing page content dynamically based on the url

Is it possible to change the content on a webpage based on the URL ?
For example, when someone visits:
example.com/dyanmictextpage.html/?utm_source=google&utm_campaign=dynamictext&utm_term=hello-world
I'd like to update a specific piece of text on the page to then say "Hello World" that's based on the last part of the URL under "utm_term=hello-world"
The code would need to auto insert whatever is after "utm_term=" and remove the hyphen and capitalise the first letters of each word.....
Do you know how??
var message = '';
var query = document.location.search.substring(1); // Remove leading '?'
var params = query.split('&');
// Get 'utm_term' from the request parameters
for (var i = 0; i < params.length; i++) {
var key = params[i].split('=')[0];
if (key === 'utm_term') {
message = params[i].split('=')[1];
break;
}
}
if (message.length > 0) {
// Split the message by words and capitalize the first letter of each word
var words = message.split('-');
for (var i = 0; i < words.length; i++) {
words[i] = words[i].charAt(0).toUpperCase() + words[i].substring(1);
}
// Finally, put the message to HTML (say, to element with id="message")
document.getElementById('message').innerHTML = words.join(' ');
}
You can - a good place to start is to break down your problem into smaller problems, and solve it piece by piece.
The first thing you need to do is get the query string values from the URL (i.e. utm_term=hello-world):
How can I get query string values in JavaScript?
Once you've got those, you'll need to dynamically replace things like hyphens so you can work the data into the format you want:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FString%2Freplace
Once you've done that, you can inject content into the page. I'll leave that bit for you to look up.

removing BBcode from textarea with Javascript

I'm creating a small javscript for phpBB3 forum, that counts how much character you typed in.
But i need to remove the special characters(which i managed to do so.) and one BBcode: quote
my problem lies with the quote...and the fact that I don't know much about regex.
this is what I managed to do so far but I'm stranded:
http://jsfiddle.net/emjkc/
var text = '';
var char = 0;
text = $('textarea').val();
text = text.replace(/[&\/\\#,+()$~%.'":*?<>{}!?(\r\n|\n|\r)]/gm, '');
char = text.length;
$('div').text(char);
$('textarea').bind('input propertychange', function () {
text = $(this).val();
text = text.replace(/[&\/\\#,+()$~%.'":*?<>{}!?\-\–_;(\r\n|\n|\r)]/gm, '');
char = text.length;
$('div').text(char);
});
You'd better write a parser for that, however if you want to try with regexes, this should do the trick:
text = $('textarea').val();
while (text.match(/\[quote.*\[\/quote\]/i) != null) {
//remove the least inside the innermost found quote tags
text = text.replace(/^(.*)\[quote.*?\[\/quote\](.*)$/gmi, '\$1\$2');
}
// now strip anything non-character
text = text.replace(/[^a-z0-9]/gmi, '');
I'm not sure if this would work, but I think you can replace all bbcodes with a regex like this:
var withoutBBCodes = message.replace(/\[[^\]]*\]/g,"");
It just replaces everything like [any char != ']' goes here]
EDIT: sorry, didn't see that you only want to replace [quote] and not all bbcodes:
var withoutBBQuote = message.replace(/\[[\/]*quote[^\]]*\]/g,"");
EDIT: ok, you also want quoted content removed:
while (message.indexOf("[quote") != -1) {
message = message.replace(/\[quote[^\]]*\]((?!\[[[\/]*quote).)*\[\/quote\]/g,"");
}
I know you already got a solution thanks to #guido but didn't want to leave this answer wrong.

Categories

Resources