So the goal of this task is translate english input values into french and vice versa. The problem here is that I don't know how to split the whole input by spaces to get all the words one by one and translate them one by one. Thank you :)
function translateInput(){
for(i = 0; i < ('input').length; i++){
('input').eq(i).val(('value').eq(i).text());
}
}
var translateText = function() {
var translationType = document.getElementById('translation').value;
if (translationType === 'englishToFrench') {
console.log('translation used: English to French');
return 'code1';
}else if(translationType === 'frenchToEnglish'){
console.log('translation used: French to English');
return 'code2';
}else{
return "No valid translation selected.";
}
};
You can use the split function to split the string at its spaces into an array.
var str = YOUR_STRING;
var array = str.split(" ");
http://www.w3schools.com/jsref/jsref_split.asp
Then you can loop through the array and translate word by word.
var arrayLength = array.length;
for (var i = 0; i < arrayLength; i++) {
alert(array[i]);
//Translate string
}
Or you can use a Regular Expression, by the way you can practice in a Regex Playground.
var myString = "Hello, my name is JavaScript";
var tokens = a.match(/\w+'?\w*/g); //Assuming you can take words like {"Bonsanto's", "Asus'"}
tokens.forEach(function(word){
console.log(word);
});
Related
i need to split a tamil word by character and print it using javascript.
Example :
Input - ஆண்டாள்
output - ஆ
ண்
டா
ள்
can someone help me.
To take each individual character of the string and print it separately you’d want to do:
var myString = "ஆண்டாள்";
var myArray =[];
for(var i = 0; i<myString.length; i++){
myArray.push(myString.charAt(i));
}
//Then print each character however you want example:
for(var i=0; i<myArray.length; i++){
console.log(myArray[i]);
}
If you don't want each character saved in an array you can also do:
var myString = "ஆண்டாள்";
for(var i = 0; i<myString.length; i++){
console.log(myString.charAt(i));
}
Split tamil word by character using javascript...
Input - ஆண்டாள்
Output - ஆ,ண்,டா,ள் (array)... code works 100%
str = "ஆண்டாள்";
var diacritics = {'\u0B82':true,'\u0BBE':true, '\u0BBF':true,
'\u0BC0':true, '\u0BC1':true, '\u0BC2':true, '\u0BC6':true,
'\u0BC7':true, '\u0BC8':true, '\u0BCA':true, '\u0BCB':true,
'\u0BCC':true, '\u0BCD':true, '\u0BD7':true};
var str1 = str.split('');
var Tamil = [];
for(var i = 0; i != str1.length; ++i){
var ch = str1[i];diacritics[ch] ?(Tamil[Tamil.length - 1] +=
ch) : Tamil.push(ch);
}
alert(Tamil);
one more best way is below
str = "ஆண்டாள்";
console.log(str.match(/[\u0b80-\u0bff][\u0bbe-\u0bcd\u0bd7]?/gi));//return ["ஆ", "ண்", "டா", "ள்"]
I am trying to check if the input string is the same as the reversed output string, and if so, it should display reversed word.
var word = "cel";
var reverseWord = "lec";
for (i=0; i < word.length; i++) {
for (j=0; j < reverseWord.length; j++) {
if (word[i] === reverseWord[j] && word[i+1] === reverseWord[j+1] && word[i+2] === reverseWord[j+2]) {
console.log("reverseWord----->");
}
}
}
If you want to check if a reversed string is the same as another string, simply use below code
var word = "cel";
var reverseWord = "lec";
console.log(word.split("").reverse().join("") === reverseWord);
Without using the reverse method
var word = "cel";
var reverseWord = "lec";
var arr = [];
for(i=word.length-1;i>=0;i--){
arr.push(word[i]);
}
var new_word = arr.join("");
if(new_word === reverseWord){
console.log("true");
}
else{
console.log("false");
}
So you can use an array to push individual characters of the string into it in reverse order using a loop and convert the array back into a string using join() method and do the check. Hope this helps.
The code below doesn't work why?
function titleCase(str){
var newStr = str.split(" "); //split string turn it into seperated words[]
var resutl;
for(vari=0; i < newStr.length; i++){ //iterate all words
var result = newStr[i].charAt(0).toUpperCase +
// find first letter and turn it into capital
newStr[i].subString(1).toLowerCase();
}
return result.join(" ");
}
result in your code is a string, not an array. you cannot join a string.
each iteration of the loop you are replacing the variable result with a new word. you need to initialize a result array [] and push each result onto the array, then join the array after the loop has completed.
The result needs to be an array and also you have some typos in your code, e.g. missing ()
function titleCase(str) {
var newStr = str.split(" ");
var result = [];
for (var i = 0; i < newStr.length; i++) {
result.push(newStr[i].charAt(0).toUpperCase() + newStr[i].substring(1).toLowerCase());
}
return result.join(' ');
}
var str = 'hELLO wORLD';
document.write(titleCase(str));
Try using regular expression
var data = "The mission is to turn each word's first letter into capital";
data = data.replace(/ (.)/g,function(w){return w.toUpperCase()});
drawback :this will not capitalize the first character.
Explode the string on spaces and iterate it with the function below:
function ucfirst(str) {
str += ''; // make sure str is really a string
var f = str.charAt(0).toUpperCase();
return f + str.substr(1);
}
You may try this :
function titleCase(str){
var newStr = str.split(" ");
var result = [];
for(var i=0; i < newStr.length; i++){
result.push(newStr[i].charAt(0).toUpperCase() +
newStr[i].substring(1).toLowerCase());
}
return result.join(' ');
}
Another Approach:
function titleCase(str){
var words = str.split(" ");
return words.map(function(word){
return word.charAt(0).toUpperCase() + word.substring(1).toLowerCase();
}).join(" ");
}
I'm working on alternating the case of a string (for example asdfghjkl to AsDfGhJkL).
I tried to do this. I found some code that is supposed to do it, but it doesn't seem to be working.
var str="";
var txt=document.getElementById('input').value;
for (var i=0; i<txt.length; i+2){
str = str.concat(String.fromCharCode(txt.charCodeAt(i).toUpperCase()));
}
Here's a quick function to do it. It makes the entire string lowercase and then iterates through the string with a step of 2 to make every other character uppercase.
var alternateCase = function (s) {
var chars = s.toLowerCase().split("");
for (var i = 0; i < chars.length; i += 2) {
chars[i] = chars[i].toUpperCase();
}
return chars.join("");
};
var txt = "hello world";
console.log(alternateCase(txt));
HeLlO WoRlD
The reason it converts the string to an array is to make the individual characters easier to manipulate (i.e. no need for String.prototype.concat()).
Here an ES6 approach:
function swapCase(text) {
return text.split('').map((c,i) =>
i % 2 == 0 ? c.toLowerCase() : c.toUpperCase()
).join('');
}
console.log(swapCase("test"))
You should iterate the string and alternate between upper-casing the character and lower-casing it:
for (var i=0; i<txt.length; i++) {
var ch = String.fromCharCode(txt.charCodeAt(i);
if (i % 2 == 1) {
ch = ch.toUpperCase();
} else {
ch = ch.toLowerCase();
}
str = str.concat(ch);
}
I need to achieve something like the following code, where if a user entered for example (you are bad), it shows an alert. The below code isn't working because it alerts for the words (you are) only without reading what's in badAppend.
var badAppend= ["freak", "ugly", "bad"]
var badWords = [("you are"+badAppend)];
if((badWords)
{
alert("you cannot use this word/sentence");
return false;
}
I'm trying to ahcieve this to avoid doing like the following:
var badWords = ["you are bad", 'you are ugly", "you are freak"];
etc..
I'd really appreciate it much if anyone can help with this. regards.
A more vanilla JavaScript way, on this one you do a "blacklist" check first against an array of "Bad Words" printing only the sentences that are allowed:
var words = document.getElementById('userInput').value.split(" ");
var badWords = ['array', 'of', 'bad', 'words'];
for (i = 0; i < words.length; i++) {
for (ii = 0; ii < badWords.length; ii++) {
var exists = words.indexOf(badWords[ii]);
if (exists != -1) {
words.splice(exists, 1);
}
}
var result = document.getElementById('notInside');
result.innerHTML += words[i];
result.innerHTML += "</br>";
}
I know he's using jQuery but just as another example to do this for other people that might need it. If you need to only display words that ARE in the array just do:
var words = document.getElementById('userInput').value.split(" ");
var badWords = ['array', 'of', 'bad', 'words'];
for (ii = 0; ii < badWords.length; ii++) {
var exists = words.indexOf(badWords[ii]);
if (exists > -1) {
var result = document.getElementById('inside');
result.innerHTML += words[exists];
result.innerHTML += "</br>";
}
}
var newWords = $(badAppend).map(function(item) { return "you are " + item; });
This will give you
newWords = [ "you are freak", "you are ugly", "you are bad" ];
I would do something like this,
var match = $('div.text').text().match(/[yY]ou(('re)|(\sare))\s\w+/g);
if(match){
match = match.map(function(item){
return (item.substring(item.lastIndexOf(" ")+1)).toLowerCase();
});
var match2 = $(match).filter(badWordsArray);
if(match2.length > 0){
console.log('Bad word!');
}else{
console.log('Input is clean!');
}
}else{
console.log('Input is clean!');
}
Change the text selector in the first line to whatever you need.
This will go through all the text that user entered, matches all the words which were followed by one of these:
You are
You're
you are
You are
The match variable will be an array containing all those words, then you can filter it based on your bad word array to see if there was any bad word.
If there is non of those four "you are"s in the code it just logs the input is clean, otherwise it checks for bad words in lowercase.
If you are sure that you just need to match 'you are' exactly, you can replace the regex with this one, it will run faster too. /(you\sare)\s\w+/g
From what I understand, you have a dictionary of bad words and you are trying to prevent user from using those words. In that case, you can do the following:
var containsBadWords = function(words){
var badWords = ['bad', 'ugly', 'freak' /* ...*/];
var badWordCount = 0;
words.forEach(function(word){
if(badWords.indexOf(word)>-1) badWordCount++;
});
return badWordCount;
}
var userWords = 'i am bad you are bad';
var result = containsBadWords(userWords.split(' '));
if(result>0) alert();