Limiting length of each word in a string - javascript

Is there a way to limit the length of each word in a string?
For example:
Loop through each word in a string
If a word is longer than X amount of characters, display a pop up message and do not submit the form.
Edit: My final code:
$("#comment-form").submit(function(event) {
var str = $("#comment-box").val(), limit = 135;
var wordList = str.split(' ');
$(wordList).each(function(i, word) {
if(word.length > limit) {
alert("Your comment has a string with more than " + limit + " characters. Please shorten it.");
event.preventDefault();
}
});
});

Try this:
var str = "This is the test string that contains some long words";
var wordList = str.split(' ');
var limit = 4;
$(wordList).each(function(i, word){
if(word.length >= limit){
alert(word);
}
});

You can use the following function
<script>
var string = "Please be sure question to answer the question";
function checkWordLength(string)
{
var string_array = string.split(" ");
for(var i=0; i<string_array.length; i++)
{
var word = string_array[i];
var word_length = word.length;
if(word_length>6) return false;
}
}
checkWordLength(string);
</script>

jsFiddle
function CheckString(string, character_limit)
{
var word = /\w+/igm;
var match;
while((match = word.exec(string)) !== null) {
if(match[0].length > character_limit)
{
alert(match[0]);
return false;
}
}
return true;
}
var character_limit = 5;
var string = 'this is a string of words and stuff even';
CheckString(string, character_limit);
This example uses regular expressions when it returns false make sure to either return false from the onSubmit method of your form.

Related

Javascript - how to render an output by typing three (or more) alphabets into the input?

I am making an html page which is a typer of a foreign script.
my progress: HERE
Here's the entire javascript:
function getReplacedText(latinText) {
if (!latinText) {
return "";
}
var replacedText = "";
for (var i = 0, len = latinText.length; i < len; i++) {
var curLetter = latinText[i];
var pos1Txt = latinText[i + 1];
var pos2Txt = latinText[i + 2];
if (!(curLetter == "")) {
var dualLetter = latreplaced[curLetter + pos1Txt];
if (dualLetter) {
replacedText += dualLetter;
i++;
continue;
}
}
replacedText += latreplaced[curLetter] || curLetter;
}
return replacedText;
}
var latreplaced = {
"u":"う",
"ku":"く",
"tsu":"つ",
};
function onLatinTextChange(txt) {
var replacedTextareaElem = document.getElementById("replaced_textarea");
var div = document.createElement("div");
var replacedHtmlEntities = getReplacedText(txt);
div.innerHTML = replacedHtmlEntities;
replacedTextareaElem.value = div.innerText;
}
The purpose of this project is to create a virtual phonetic keyboard to type certain forign scripts by only using Latin alphabets, without its keyboard setting installed.
Basically, if you enter an alphabet into the input <textarea>, it renders its corresponding foreign alphabet. (For instance, input 'u' > output 'う', input 'ku' > output 'く')
Here is my problem: So far I have enabled rendering an output when one or two alphabet is typed into the input box. But I cannot figure out how to enable the same by entering three alphabets. (For instance, input 'tsu' > output 'つ')
"u":"う", // <- can convert
"ku":"く", // <- can convert
"tsu":"つ", // <- cannot convert!
In the javascript code, there is a var called dualLetter, which goes by the following script:
var dualLetter = latreplaced[curLetter + pos1Txt];
How can I edit this part of code (or the entire javascript) to be able to convert 3 or more input alphabets? Do I need to make var tripleLetter, or create a whole new system? Any alternative ways would also be helpful.
[edit] a solution inspired by your code :
I changed the main function but this definitively works
live demo : https://jsfiddle.net/alias_gui3/wds426mq/12/
source code :
var dictionnary = {
"u":"う",
"ku":"く",
"tsu":"つ",
"test for spaces": "😍"
};
var maxLength = Object.keys(dictionnary)
.reduce((a, b) => a.length > b.length ? a : b) // get the longest word
.length; // and it's length
function translate (text) {
var translated = "";
var cur = 0;
while (cur < text.length) {
var testedPhoneme;
var symbol = undefined;
for (var length = maxLength; length > 0; length --) {
testedPhoneme = text.substr(cur, length);
if (dictionnary[testedPhoneme]) {
symbol = dictionnary[testedPhoneme];
break; // stop the loop
}
}
if (symbol) {
translated += symbol;
cur += testedPhoneme.length;
}
else {
translated += text[cur]
cur++;
}
}
return translated
}
function onLatinTextChange(txt) {
var replacedTextareaElem = document.getElementById("replaced_textarea");
var div = document.createElement("div");
var replacedHtmlEntities = translate(txt);
div.innerHTML = replacedHtmlEntities;
replacedTextareaElem.value = div.innerText;
}
[previous post] a simple solution :
I suggest you split your text using spaces
If i understand well, you want to type u ku tsu to get うくつ, not ukutsu, if this is right then something like that could work :
const dictionnary = {
"u": "う",
"ku": "く",
"tsu": "つ"
var phonemes = text.split(' ') // split text by spaces
var translatedArray = phonemes.map(function (phoneme) {
return dictionnary[phoneme] || phoneme
// will return the latin phoneme if it is not in the dictionnary
})
translatedString = translatedArray.join('')

How to find a word in a string?

The challenge is to "find Waldo." I'm trying to figure out how to find a word in a function/string." Return the index of where in the string 'Waldo' starts."
function findWaldo(str) {
var waldoPosition;
return waldoPosition
}
Simple task to do:
function findWaldo(str) {
return str.indexOf("waldo"); //the string you are looking for
}
It is explained quite well here.
There should be a library that does it easily, like string.indexOf, but you can do it manually with this algorithm:
int count = 0;
string yourText = "This is waldo?";
string toSearch = "waldo";
for (int x = 0; x < yourText.Lenght; x++)
{
if(yourText[x] == toSearch[0])
if((count + 1) == toSearch.Lenght)
return x;
else
count = 0;
//here we'd say ehh there's not Waldo on the string
}
To find a word or letter you can use x.indexOf method, hope to below code helps.
// Question
const findWord = (str, findWord) =>{
let total = ""
let error = false
let errorMessage = "";
if(str != null && str != ""){
error = false
if(!str.indexOf(findWord)){
total = `there is no ${findWord} in str peremeter.
`
}else{
total = `the position of ${findWord} is ${str.indexOf(findWord)}`
}
}else{
error = true;
errorMessage = "Please fill the str perimeter."
return errorMessage
}
return total
}
// Calling Function
console.log(findWord("Hello World", "World"))

How would I write a script that reads a series of strings, and outputs in an HTML5 textarea only those strings beginning with the character “b.”?

I need to write a script that reads a series of strings and outputs in a textarea only those strings beginning with the character “b.”
I was using the split element to create individual tokens, but I don't know how to then search the created tokens. I need it to take the words out of an inputed sentence in browser, and return only those that begin with the letter "b"
What function should i use to search the tokens created from the split function, or is there an easier way to search the sub-strings to print out the results I need?
function findStrings(inputString) {
var inputArray = [],
inputArrayLen,
holdArray = [],
pat = /\bb/i;
inputArray = inputString.split(" ");
inputArrayLen = inputArray.length;
for (var i = 0 ; i < inputArrayLen; i++) {
if (pat.test(inputArray[i])) {
holdArray.push(inputArray[i])
}
}
return holdArray.join(',')
var inputString = document.getElementById( "inputField" ).value
var results = document.getElementById( "results" );
var outputString = findStrings(inputString)
results.innerHTML = "<p>The sentence split into words is: </p>" +
"<p class = 'indent'>" + outputString + "</p>";
}
// register click event handler for searchButton
function start()
{
var splitButton = document.getElementById( "splitButton" );
splitButton.addEventListener( "click", splitButtonPressed, false );
} // end function start
window.addEventListener( "load", start, false );
You could use this function to search a string and return a string containing all words that begin with a b or B.
function findStrings(inputString) {
var inputArray = [],
inputArrayLen,
holdArray = [],
pat = /\bb/i;
inputArray = inputString.split(" ");
inputArrayLen = inputArray.length;
for (var i = 0 ; i < inputArrayLen; i++) {
if (pat.test(inputArray[i])) {
holdArray.push(inputArray[i])
}
}
return holdArray.join(',')
}
Then you could add it to the HTML like this
var inputField = document.getElementById( "inputField" );
var results = document.getElementById( "results" );
function splitButtonPressed (){
var inputString = inputField.value,
outputString = findStrings(inputString);
results.innerHTML = "<p>The sentence split into words is: </p>" +
"<p class = 'indent'>" + outputString + "</p>";
}
// register click event handler for searchButton
function start() {
var splitButton = document.getElementById( "splitButton" );
splitButton.addEventListener( "click", splitButtonPressed, false );
} // end function start
window.addEventListener( "DOMContentLoaded", start, false );
You're on the right path by splitting the sentence into tokens with split(). You then get an array of all the tokens in your sentence. All that remains to do is to iterate over that array and filter out any tokens that doesn't start with the letter b, like this:
var sentence = "My baby has a nice belly";
var tokens = sentence.split(" ");
var bTokens = tokens.filter(function(token) {
return /^b/.test(token);
}).join(" ");
document.getElementById("mytextarea").value = bTokens;
You can just use the chatAt function.
for (i = 0; i < tokens.length; i++) {
var mystring = tokens[i];
if (mystring.charAt(0) == 'b') {
// append to textarea
}
}
charAt(0) gets the first character of a string. Do that for each of your substrings.

Using separators in JS

I'm currently writing a program that uses ";" as a seperator and extracts the url up until that point upon searching the content.
So it has the format:
name;surname
In searching the given arrays... I decided to go the extra mile and test for arrays without the ";" but this has confused the program - it has no idea of the ";" position anymore and this throws a spanner in the works!
Here is my code so far - many thanks in advance!
pages =
[
"The first", "An;alternative;page", "Yet another page"
]
u_c_pages =
[
"www.cam.ac.uk;"+pages[0]
,
"www.warwick.ac.uk"+pages[1]
,
"www.kcl.ac.uk;"+pages[1]
,
"www;"+pages[2]
]
var pattern5 = prompt('5) Please enter a search term:');
function url1_m1(u_c_pages,pattern)
{
var seperator = [];
var seperatorPos = [];
if(pattern)
{
for (var i = 0; i < u_c_pages.length; i++)
{
var found = true;
if((u_c_pages[i].indexOf(";"))<0)
{
found=false;
}
else
{
seperator[seperator.length] = i;
seperatorPos[seperatorPos.length] = (u_c_pages[i].indexOf("|"));
}
}
if(seperator.length==0)
{
return("Nothing found!");
}
else
var found2 = "";
{
for (var j = 0; j < seperator.length; j++)
{
if(u_c_pages[j].substring(seperatorPos[j],u_c_pages[j].length-1).toLowerCase().indexOf(pattern.toLowerCase()) >= 0)
{
found2 = (u_c_pages[j].substring(0,seperatorPos[j]));
break;
}
}
return(found2)
}
}
else
{
// only returned when the user decides to type in nothing
return("Nothing entered!");
}
}
alert(url1_m1(u_c_pages,pattern5));
enjoy the power of regex:
on JSFiddle
pages = ["The first", "An;alternative;page", "Yet another page"];
u_c_pages = [
"www.lboro.ac.uk;"+pages[0],
"www.xyz.ac.uk;"+pages[1],
"www.xyz.ac.uk;"+pages[1],
"www;"+pages[2]
];
var pattern5 = prompt('5) Please enter a search term:');
function url1_m1(u_c_pages,pattern)
{
// escape search pattern
pattern = pattern.toLowerCase().replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&')
pattern = new RegExp('^([^;]+);.*?' + pattern, 'i');
var result = null;
for(var i=0;i<u_c_pages.length;i++) {
if((result = u_c_pages[i].match(pattern))) {
return result[1];
}
}
return false;
}
alert(url1_m1(u_c_pages,pattern5));
You can use String.split(";") to split a string into segments. The parameter is the seperator.

Count BB code occurence

I want to count number of occurence of BB code like word (example: [b] [/b]).
I tried
(str.match(/\[b\]/g) str.match(/\[\/b\]/g))
None of this worked, please help !!!
Edit
document.getElementById('textarea').value = 'HIiiiiiiiiiii [b]BOld[/b]';
var str = document.getElementById('textarea').value;
Answer:
if (str.match(/\[b\]/g).length == str.match(/\[\/b\]/g)).length) {alert("Fine");}
This regex will match a BB code opening tag:
str.match(/\[[a-z]*\]/g)
Edit: Here's some code that will do exactly what you want including creating an array of errors listing all missing closing tags. This code uses the underscore library for the groupBy() call.
jsFiddle
var bbcode = 'HI[i]iii[i]iii[/i]iii [b]BOld[/b] yahhh [img]url[/img]';
var matches = bbcode.match(/\[[a-z]*\]/g); //get the matches
var tags = _.groupBy(matches, function(val) {
val = val.substring(1, val.length-1);
return val;
});
var errors = [];
for (var tag in tags) {
var regex = '\\\[/' + tag + '\\\]';
if (bbcode.match(regex).length != tags[tag].length) {
errors.push('Missing a closing [/' + tag + '] tag');
}
}
console.log(errors);
Replace occurences until there aren't any; keep track of the amount on the way:
var regexp = /\[[a-z]\](.*?)\[\/[a-z]\]/i;
var str = "test [b]a[/b] test [i]b[/i] [b]d[/b] c";
var newstr = str;
var i = 0;
while(regexp.test(newstr)) {
newstr = newstr.replace(regexp, "");
i++;
}
alert(i); // alerts 3

Categories