How to tell if a string contains HTML entity (like &)? - javascript

I'm trying to write a function that checks a parameter against an array of special HTML entities (like the user entered '&amp' instead of '&'), and then add a span around those entered entities.
How would I search through the string parameter to find this? Would it be a regex?
This is my code thus far:
function ampersandKiller(input) {
var specialCharacters = ['&', ' ']
if($(specialCharacters).contains('&')) {
alert('hey')
} else {
alert('nay')
}
}
Obviously this doesn't work. Does anyone have any ideas?
So if a string like My name is & was passed, it would render My name is <span>&</span>. If a special character was listed twice -- like 'I really like &&& it would just render the span around each element. The user must also be able to use the plain &.

function htmlEntityChecker(input) {
var characterArray = ['&', ' '];
$.each(characterArray, function(idx, ent) {
if (input.indexOf(ent) != -1) {
var re = new RegExp(ent, "g");
input = input.replace(re, '<span>' + ent + '</span>');
}
});
return input;
}
FIDDLE

You could use this regular expression to find and wrap the entities:
input.replace(/&| /g, '<span>$&</span>')
For any kind of entity, you could use this too:
input.replace(/&(?:[a-z]+|#\d+);/g, '<span>$&</span>');
It matches the "word" entities as well as numeric entities. For example:
'test & & <'.replace(/&(?:[a-z]+|#x?\d+);/gi, '<span>$&</span>');
Output:
test & <span>&</span> <span><</span>

Another option would be to make the browser do a decode for you and check if the length is any different... check this question to see how to unescape the entities. You can then compare the length of the original string with the length of the decoded. Example below:
function htmlDecode(input){
var e = document.createElement('div');
e.innerHTML = input;
return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
}
function hasEntities(input) {
if (input.length != htmlDecode(input).length) {
return true;
}
return false;
}
alert(hasEntities('a'))
alert(hasEntities('&'))
The above will show two alerts. First false and then true.

Related

Caps and Lowercase input that also generates in output

I've been trying to put together an input where the text automatically capitalizes the first letter of each word and makes all other letters lowercase for that word. I had some success using that for just making everything lower case after the first letter for the input with this:
<input type = "text" size="8" name="textfield1" id="textfield1" />
with the javascript being
document.getElementById('textfield1').addEventListener("keyup", () => {
var inputValue = document.getElementById('textfield1')['value'];
if (inputValue[0] === ' ') {
inputValue = '';
} else if (inputValue) {
inputValue = inputValue[0].toUpperCase() + inputValue.slice(1).toLowerCase();
}
document.getElementById('textfield1')['value'] = inputValue;
});
I tried adding map(), split(), and join() in various ways based off of lessons I've found (I'm learning on my own, no formal training since high school) for use in a string with the console.log methods but I'm confused on how I can apply this to an input. It would take too long to note everything I've tried but one thing I did was this:
document.getElementById('textfield1').addEventListener("keyup", () => {
var inputValue = document.getElementById('textfield1')['value'];
if (inputValue[0] === ' ') {
inputValue = '';
} else if (inputValue) {
input.content = input.content.split(' ').map(function(inputValue) {
return inputValue[0].toUpperCase() + inputValue.slice(1).toLowerCase();
}).join(' ');
}
document.getElementById('textfield1')['value'] = inputValue;
});
I'm not sure what I'm missing here. I'm sure there's something that I'm not seeing or understanding. I also tried looking to see if there was something similar listed on here or elsewhere in relation to this and inputs but I didn't see anything specific to what I was looking for.
I want the input to remain the same for what comes up with the output into another box when it gets copied over.
Example of what I'm trying to do is:
input of textfield: heLlo OuT thERe!
output to another textarea with the click of a button: Hello Out There!
Your second version would be correct. However in this code:
else if (inputValue) {
input.content = input.content.split(' ').map(function(inputValue) {
return inputValue[0].toUpperCase() + inputValue.slice(1).toLowerCase();
}).join(' ');
}
You started to use some input.content instead of the inputValue variable. Most probably yout mistake lies there.
You can use this regex replace to change a sentence to Proper Case:
const regex = /\b(\w)(\w*)/g;
const input = 'Fix this lower and UPPER to Proper'
let result = input.replace(regex, function(m, c1, c2) {
return c1.toUpperCase() + c2.toLowerCase()
});
console.log('result: ', result);
// => 'Fix This Lower And Upper To Proper'
Explanation of regex:
\b -- word boundary
(\w) -- capture group 1: a singe word character
(\w*) --capture group 2: zero to multiple word characters
g -- flag for global, e.g. run pattern multiple times
replace function: parameter c1 contains capture group 1, c2 contains capture group 2

Wix Form Validation

First off, I am a complete noob. I have just recently started getting good with python and have close to zero knowledge regarding javascript and corvid for wix. I am looking through documentation but I can't figure out how to do the following: When a user fills out a field, let's say a phone number field, how do you validate whether that field has any alphabetical characters or "+" or "-" etc or not?
I am trying to do something like this:
$w.onReady(function () {
$w("#input1").onCustomValidation( (value, reject) => {
if( input1 is anything but an integer ) {
reject("Only Numbers. No '-', '.', '()', '+', or any alphabetical characters");
}
} );
});
I feel like I am close but have no idea. Any help is appreciated
To answer your question:
Includes Function
You would want to use the .includes() function native to javascript which returns a boolean of if it is or isn't included. If you need the string index of each occurrence you would need to use a for loop as shown below.
var string = "+54 2453-2534-242";
for(int i = 0; i < string.length(); i++){
if(string.substr(i,1) === "-"){
console.log(i);
}
}
Includes Function
Replace Function
Below is an example of how to use this function.
If you wish to remove these or one of these characters you can use the .replace() function or the .split() and .join() functions.
const string = "+53 573-2566-242";
const character_1 = "+";
const character_2= "-";
// Includes
console.log(string + ".includes(+):", string.includes(character_1));
console.log(string + ".includes(-):",string.includes(character_2));
// Replace Singular
var new_string = string.replace(character_1,'');
console.log(new_string);
// Replace Multiple
var new_string2 = string.split(character_2).join("");
console.log(new_string2);
Replace Funtion
If you are still stuck, please feel free to comment
Edit
To check if there are any alpha-numeric characters in a string. You can simply use the .replace() function and compare it. As seen below:
var string = "abc546"; // Your Phone Number Input
var string_converted = string.replace(/\D/g,'');
if(string !== string_converted){
console.log("Contains Characters that are not of type NUMBER!");
console.log(`${string} vs ${string_converted}`);
}
In your case, you could use the code below:
$w.onReady(function () {
$w("#input1").onCustomValidation( (value, reject) => {
// Assuing *value* is your input
var converted = value.replace(/\D/g,'');
if(value !== converted){
// Regective Statment Here..
}else{
// All good! (No Alph-numeric Characters)
}
});
});

How to replace specific parts in string with javascript with values from object

I want to make custom replacer method for my HTML output. But I can't figure it out. I guess it should be done with String.match and replace somehow.
I have some "error codes" in my string that always start with _err_ and I have a JS object with values.
What I want to achieve:
Find all string parts (error codes) that starts with _err_
Get correct key for my object - error code without _err_
Find value from Lang object
Replace error code with correct Lang value.
Some error codes may appear multiple times.
var content = "Looks like you have _err_no_email or _err_no_code provided";
var Lang = {
'no_email' : "No email",
'no_code' : "No code"
};
I can do it other way around. So I cycle the Lang object and replace those in string.
It would be something like this if using underscore:
function replaceMe() {
_.each(Lang, function(value, key) {
content = content.replace(new RegExp('_err_' + key,'g'), value);
});
console.log(content);
};
But if it can be done faster with my first idea then I want to know how.
A simple regex should do the trick:
var content = content.replace(/\b_err_(.+?)\b/g, function(match, errorName) {
return Lang[errorName] || match;
});
This assumes that you do not want strings like "blah_err_blah" to be replaced, and defaults to not replacing the text if the error cannot be found in your Lang object.
var replace = function(str, object, regexp) { //if property not found string is not replaced
return String(str).replace(regexp || (/\\?\{([^{}]+)\}/g), function(match, name) {
return (object[name] != null) ? object[name] : match;
});
}
This is a format function I've used in several projects thats quite efficient. Matches {prop} by default to {prop:'val'} but you can pass a regex for example maybe in your case /_err_+\S/g so it matches other tokens in your string.
So you can do:
var content ="Looks like you have {no_email} or {no_code} provided";
var Lang = {
'no_email' : "No email",
'no_code' : "No code"
}
var formatted = replace(content, lang);
Or for your original string stealing the other answers regex:
var formatted = replace(content, lang, /_err_([^\s]+)/g)
You can use a callback function, that look if a key matching the error code exists in your Lang object, and if so returns the value of that (and otherwise just the key itself, thereby doing no replacement, like so:
content.replace(/_err_([a-z_]+)/gi, function(fullmatch, key) {
return Lang[key] ? Lang[key] : fullmatch;
});
The first parameter passed to the function will be the full match, and the second parameter key will just be that part grouped by the bracktes.
And then, if Lang contains a (non-falsy) value for key, that’ll be returned, otherwise just the fullmatch value, so that that part of the string gets “replaced” with itself.
See it in action here: http://jsfiddle.net/VZVLt/1/
One more variation with split
content = content
.split('_err_')
.map(function(str, index){
if (index === 0)
return str;
var whitespace = str.indexOf(' '),
key = str.substring(0, whitespace)
return Lang[key] + str.substring(whitespace);
})
.join('')
;

Javascript / Jquery Search if a word exists in a string

I'm definitely a newbie and am trying a practice project.
Its basically an anagram game where the user clicks on certain letters to put together a word.
I now need to check that it is actually a word. I've made a text file containing all the words in the dictionary (copied from someones website as its just a practice project). I've managed to get it so that if I can console.log the words.
function Searchtext(){
$.get('words.txt', function(data) {
console.log(data);
}, 'text');
}
Now I want to search the words to see if the player's answer ( a string which is declared in a variable called playeranswer ) is in the list. I don't need it to return the word, only whether it is there or not. N.B. it has to be exact so that for example if the user entered "ender" which isnt a word, it wont come back true because it finds the word "render". Maybe something with the .length will help?
How would I go about doing this?
Thanks for any help.
Since $.get is asynchronous, you'll have to set it up a little differently. I'd do this:
function Searchtext(name, callback) {
$.get('words.txt', function(data) {
data = data.split("\n");
var contains = (data.indexOf(name) > -1);
callback(contains);
}, 'text');
}
Depending on how the text file is setup, you might have to change .split("\n") (which splits up the words into an array, if they're each on a line) to .split(" ") (which splits up the words into an array, if they're separated by a space).
And you'd call it like:
SearchText(playername, function (matched) {
if (matched) {
// Name was in list
} else {
// Name wasn't in list
}
});
DEMO: http://jsfiddle.net/Fkr5B/
In the demo, I had to simulate the AJAX request.
I would use a regular expression (using a RegExp object) for this. Here is a simple example that tries to match a word in two different strings of words:
var word_to_match = 'ender';
var string_of_words = 'a string containing the word ender, this will match';
var second_string_of_words = 'a string that will not produce a match';
//use \b to match on word boundaries
var filter = new RegExp('\\b' + word_to_match + '\\b', 'gi');
if(string_of_words.match(filter)) {
alert('found word: ' + word_to_match);
} else {
alert('did not find word: ' + word_to_match);
}
if(second_string_of_words.match(filter)) {
alert('found word: ' + word_to_match);
} else {
alert('did not find word: ' + word_to_match);
}
You'll see the first if statement passes, while the second fails. A little reading might be required, but you should be able to expand this example to fit your use case.
You should first parse the data variable and place the words into an Array.
Then you can test if the user entered a valid word by checking if your Array contains that word.
var Dict = new Array("render", "bender", "word");
function isValid(word){
if(Dict.indexOf(word) == -1)
return false; //the word is not valid
return true; //the word is valid
}
I've made this simple script, hope it helps
$(document).ready(function(e) {
function parseData(data) {
$('#inpu').blur(function() {
var str_to_search = $.trim($('#inpu').val());
if(str_to_search.length) {
var search_res = data.search(str_to_search);
if(search_res != -1) {
alert('Word Valid!');
} else {
alert('Word no valid');
}
}
});
}
$.get('to_search.txt', parseData).fail(function() { alert('error');});
});

How can I improve the performance of my JavaScript text formatter?

I am allowing my users to wrap words with "*", "/", "_", and "-" as a shorthand way to indicate they'd like to bold, italicize, underline, or strikethrough their text. Unfortunately, when the page is filled with text using this markup, I'm seeing a noticeable (borderline acceptable) slow down.
Here's the JavaScript I wrote to handle this task. Can you please provide feedback on how I could speed things up?
function handleContentFormatting(content) {
content = handleLineBreaks(content);
var bold_object = {'regex': /\*(.|\n)+?\*/i, 'open': '<b>', 'close': '</b>'};
var italic_object = {'regex': /\/(?!\D>|>)(.|\n)+?\//i, 'open': '<i>', 'close': '</i>'};
var underline_object = {'regex': /\_(.|\n)+?\_/i, 'open': '<u>', 'close': '</u>'};
var strikethrough_object = {'regex': /\-(.|\n)+?\-/i, 'open': '<del>', 'close': '</del>'};
var format_objects = [bold_object, italic_object, underline_object, strikethrough_object];
for( obj in format_objects ) {
content = handleTextFormatIndicators(content, format_objects[obj]);
}
return content;
}
//#param obj --- an object with 3 properties:
// 1.) the regex to search with
// 2.) the opening HTML tag that will replace the opening format indicator
// 3.) the closing HTML tag that will replace the closing format indicator
function handleTextFormatIndicators(content, obj) {
while(content.search(obj.regex) > -1) {
var matches = content.match(obj.regex);
if( matches && matches.length > 0) {
var new_segment = obj.open + matches[0].slice(1,matches[0].length-1) + obj.close;
content = content.replace(matches[0],new_segment);
}
}
return content;
}
Change your regex with the flags /ig and remove the while loop.
Change your for(obj in format_objects) loop with a normal for loop, because format_objects is an array.
Update
Okay, I took the time to write an even faster and simplified solution, based on your code:
function handleContentFormatting(content) {
content = handleLineBreaks(content);
var bold_object = {'regex': /\*([^*]+)\*/ig, 'replace': '<b>$1</b>'},
italic_object = {'regex': /\/(?!\D>|>)([^\/]+)\//ig, 'replace': '<i>$1</i>'},
underline_object = {'regex': /\_([^_]+)\_/ig, 'replace': '<u>$1</u>'},
strikethrough_object = {'regex': /\-([^-]+)\-/ig, 'replace': '<del>$1</del>'};
var format_objects = [bold_object, italic_object, underline_object, strikethrough_object],
i = 0, foObjSize = format_objects.length;
for( i; i < foObjSize; i++ ) {
content = handleTextFormatIndicators(content, format_objects[i]);
}
return content;
}
//#param obj --- an object with 2 properties:
// 1.) the regex to search with
// 2.) the replace string
function handleTextFormatIndicators(content, obj) {
return content.replace(obj.regex, obj.replace);
}
Here is a demo.
This will work with nested and/or not nested formatting boundaries. You can omit the function handleTextFormatIndicators altogether if you want to, and do the replacements inline inside handleContentFormatting.
Your code is forcing the browser to do a whole lot of repeated, wasted work. The approach you should be taking is this:
Concoct a regex that combines all of your "target" regexes with another that matches a leading string of characters that are not your special meta-characters.
Change the loop so that it does the following:
Grab the next match from the source string. That match, due to the way you changed your regex, will be a string of non-meta characters followed by your matched portion.
Append the non-meta characters and the replacement for the target portion onto a separate array of strings.
At the end of that process, the separate accumulator array can be joined and used to replace the content.
As to how to combine the regular expressions, well, it's not very pretty in JavaScript but it looks like this. First, you need a regex for a string of zero or more "uninteresting" characters. That should be the first capturing group in the regex. Next should be the alternates for the target strings you're looking for. Thus the general form is:
var tokenizer = /(uninteresting pattern)?(?:(target 1)|(target 2)|(target 3)| ... )?/;
When you match that against the source string, you'll get back a result array that will contain the following:
result[0] - entire chunk of string (not used)
result[1] - run of uninteresting characters
result[2] - either an instance of target type 1, or null
result[3] - either an instance of target type 2, or null
...
Thus you'll know which kind of replacement target you saw by checking which of the target regexes are non empty. (Note that in your case the targets can conceivably overlap; if you intend for that to work, then you'll have to approach this as a full-blown parsing problem I suspect.)
You can do things like:
function formatText(text){
return text.replace(
/\*([^*]*)\*|\/([^\/]*)\/|_([^_]*)_|-([^-]*)-/gi,
function(m, tb, ti, tu, ts){
if(typeof(tb) != 'undefined')
return '<b>' + formatText(tb) + '</b>';
if(typeof(ti) != 'undefined')
return '<i>' + formatText(ti) + '</i>';
if(typeof(tu) != 'undefined')
return '<u>' + formatText(tu) + '</u>';
if(typeof(ts) != 'undefined')
return '<del>' + formatText(ts) + '</del>';
return 'ERR('+m+')';
}
);
}
This will work fine on nested tags, but will not with overlapping tags, which are invalid anyway.
Example at http://jsfiddle.net/m5Rju/

Categories