How to Skip Over Word in Loop in Javascript - javascript

I have the following strings:
str=["If we go to the park, we will find a big slide!"];
replacer=[["to","a"],["a","un"]];
I then iterate through str and replace each occurrence of "to" with "a" and then each occurrence of "a" with "un" and end up with:
str=["If we go un the park, we will find un big slide!"];
I understand that in this simple case I could reverse the replacer values but that is not an option for me. Is there anyway I could put some kind of disclaimer or flag with the replaced word so that when I iterate through for the next variable it skips the already replaced word?
Thanks!

try
var str=["If we go to the park, we will find a big slide!"];
function replacer(str, oldarr, newArr)
{
oldarr.forEach( function(value,index){
str = str.replace( new RegExp(value, "g"), newArr[index] );
} );
return str;
}
replacer(str[0],["to","a"],["a","un"]);

You can split str by space to array, and then iterate over each word, saving "used" index to temporary array not to overwrite it again, then join this array back to string:
var str = ["If we go to the park, we will find a big slide!"];
var replacer = [["to","a"],["a","un"]];
var ar = str[0].split(' ');
var used = [];//temporary array to hold indexes of changes values
replacer.forEach(function(v,k){
ar.forEach(function(x,i){
if(used.indexOf(i) < 0){
if(x == v[0]){
ar[i] = v[1];
used.push(i);
}
}
});
});
str = [ar.join(' ')];
console.log(str);
Output:
["If we go a the park, we will find un big slide!"]

Related

Checking the presence of multiple words in a variable using JavaScript

The code the presence of a single word in a sentence and it's working fine.
var str ="My best food is beans and plantain. Yam is also good but I prefer yam porrage"
if(str.match(/(^|\W)food($|\W)/)) {
alert('Word Match');
//alert(' The matched word is' +matched_word);
}else {
alert('Word not found');
}
Here is my issue: I need to check presence of multiple words in a sentence (eg: food,beans,plantains etc) and then also alert the matched word.
something like //alert(' The matched word is' +matched_word);
I guess I have to passed the searched words in an array as per below:
var words_checked = ["food", "beans", "plantain"];
You can construct a regular expression by joining the array of words by |, then surround it with word boundaries \b:
var words_checked = ['foo', 'bar', 'baz']
const pattern = new RegExp(String.raw`\b(?:${words_checked.join('|')})\b`);
var str = 'fooNotAStandaloneWord baz something';
console.log('Match:', str.match(pattern)[0]);
Here's a way to solve this. Simply loop through the list of words to check, build the regex as you go and check to see if there is a match. You can read up on how to build Regexp objects here
var str ="My best food is beans and plantain. Yam is also good but I prefer
yam porrage"
var words = [
"food",
"beans",
"plantain",
"potato"
]
for (let word of words) {
let regex = new RegExp(`(^|\\W)${word}($|\\W)`)
if (str.match(regex)) {
console.log(`The matched word is ${word}`);
} else {
console.log('Word not found');
}
}
var text = "I am happy, We all are happy";
var count = countOccurences(text, "happy");
// count will return 2
//I am passing the whole line and also the word for which i want to find the number of occurences
// The code splits the string and find the length of the word
function countOccurences(string, word){
string.split(word).length - 1;
}

How can I split commas and periods from words inside of string using split?

I am trying to change specific word in a string with something else. For example, I want to change 'John' in let name = 'Hi, my name is John.'; to 'Jack'.
I know how to split a string by words or characters. I also know how to remove commas, periods, and other symbols in a string. However, if I split the given string with a separator (" "), I will have 'John.' which I do not want. (I know I can switch 'John.' with 'Jack.' but assume that I have an key and value pairs in an object and I am using the values which are names {Father: Jack, Mother: Susan, ...}
I don't know how to separate a string word by word including commas and periods.
For example, if I was given an input which is a string:
'Hi, my name is John.'
I want to split the input as below:
['Hi', ',', 'my', 'name', 'is', 'John', '.']
Does anyone know how to do it?
Below is the challenge I am working on.
Create a function censor that accepts no arguments. censor will return a function that will accept either two strings, or one string. When two strings are given, the returned function will hold onto the two strings as a pair, for future use. When one string is given, the returned function will return the same string, except all instances of a first string (of a saved pair) will be replaced with the second string (of a saved pair).
//Your code here
const changeScene = censor();
changeScene('dogs', 'cats');
changeScene('quick', 'slow');
console.log(changeScene('The quick, brown fox jumps over the lazy dogs.')); // should log: 'The slow, brown fox jumps over the lazy cats.'
I think your real question is "How do I replace a substring with another string?"
Checkout the replace method:
let inputString = "Hi, my name is John.";
let switch1 = ["John", "Jack"];
let switched = inputString.replace(switch1[0], switch1[1]);
console.log(switched); // Hi, my name is Jack.
UPDATE: If you want to get ALL occurrences (g), be case insensitive (i), and use boundaries so that it isn't a word within another word (\\b), you can use RegExp:
let inputString = "I'm John, or johnny, but I prefer john.";
let switch1 = ["John", "Jack"];
let re = new RegExp(`\\b${switch1[0]}\\b`, 'gi');
console.log(inputString.replace(re, switch1[1])); // I'm Jack, or johnny, but I prefer Jack.
You can Try This ...
var string = 'Hi, my name is John.';
//var arr = string.split(/,|\.| /);
var arr = string.split(/([,.\s])/);
console.log(arr);
Using 'Hi, my name is John.'.split(/[,. ]/); will do the job. It will split commas and periods and spaces.
Edit: For those who want to keep the comma and period, here is my wildly inefficient method.
var str = 'Hi, my name is John.'
str = str.replace('.', 'period');
str = str.replace(',', 'comma');
str = str.split(/[,. ]/);
for (var i = 0; i < str.length; i++) {
if (str[i].indexOf('period') > -1) {
str[i] = str[i].replace('period', '');
str.splice(i+1, 0, ".");
} else if (str[i].indexOf('comma') > -1) {
str[i] = str[i].replace('comma', '');
str.splice(i+1, 0, ",");
}
}
console.log(str);

Make translation function not translate result again

I have made this very simplified version of a translation tool similar to Google Translate. The idea is to build this simple tool for a minority language in sweden called "jamska". The app is built up with a function that takes the string from a textarea with the ID #svenska and replaces words in the string using RegExp.
I've made an array called arr that's used in a for loop of the function as a dictionary. Each array item looks like this: var arr = [["eldröd", "eillrau"], ["oväder", "over"] ...]. The first word in each array item is in swedish, and the second word is in jamska. If the RegExp finds a matching word in the loop it replaces that word using this code:
function translate() {
var str = $("#svenska").val();
var newStr = "";
for (var i = 0; i < arr.length; i++) {
var replace = arr[i][0];
var replaceWith = arr[i][1];
var re = new RegExp('(^|[^a-z0-9åäö])' + replace + '([^a-z0-9åäö]|$)', 'ig');
str = str.replace(re, "$1" + replaceWith + '$2');
}
$("#jamska").val(str);
}
The translate() is then called in an event handler for when the #svenska textarea gets a keyup, like this: $("#svenska").keyup(function() { translate(); });
The translated string is then assigned as the value of another textarea with the ID #jamska. So far, so good.
I have a problem though: if the translated word in jamska also is a word in swedish, the function translates that word too. This problem is occurring because I'm assigning the variable str to the translated version of the same variable, using: str = str.replace(re, "$1" + replaceWith + '$2');. The function is using the same variable over and over again to perform the translation.
Example:
The swedish word "brydd" is "fel" in jamska. "Fel" is also a word in swedish, so the word that I get after the translation is "felht", since the swedish word "fel" is "felht" in jamska.
Does anyone have any idea for how to work around this problem?
Instead of looking for each Jamska word in the input and replacing them with the respective translation, I would recommend to find any word ([a-z0-9åäö]+) in your text and replace this word either with its translation if one is found in the dictionary or with itself otherwise:
//var arr = [["eldröd", "eillrau"], ["oväder", "over"] ...]
// I'd better use dictionary instead of array to define your dictionary
var dict = {
eldröd: "oväder",
eillrau: "over"
// ...
};
var str = "eldröd test eillrau eillrau oväder over";
var translated = str.replace(/[a-z0-9åäö]+/ig, function(m) {
var word = m.toLowerCase();
var trans = dict[word];
return trans === undefined ? word : trans;
});
console.log(translated);
Update:
If dictionary keys may be represented by phrases (i.e. technically appear as strings with spaces), the regex should be extended to include all these phrases explicitly. So the final regex would look like
(?:phrase 1|phrase 2|etc...)(?![a-z0-9åäö])|[a-z0-9åäö]+
It will try to match one of the phrases explicitly first and only then single words. The (?![a-z0-9åäö]) lookbehind helps to filter out phrases immediately followed by letters (e.g. varken bättre eller sämreåäö).
Phrases immediately preceded by letters are implicitly filtered out by the fact that a match is either the fist one (and therefore is not preceded by any letter) or it's not the first and therefore the previous one is separated from the current by some spaces.
//var arr = [["eldröd", "eillrau"], ["oväder", "over"] ...]
// I'd better use dictionary instead of array to define your dictionary
var dict = {
eldröd: "oväder",
eillrau: "over",
bättre: "better",
"varken bättre eller sämre": "vär å int viller",
"test test": "double test"
// ...
};
var str = "eldröd test eillrau eillrau oväder over test test ";
str += "varken bättre eller sämre ";
str += "don't trans: varken bättre eller sämreåäö";
str += "don't trans again: åäövarken bättre eller sämre";
var phrases = Object.keys(dict)
.filter(function(k) { return /\s/.test(k); })
.sort(function(a, b) { return b.length - a.length; })
.join('|');
var re = new RegExp('(?:' + phrases + ')(?![a-z0-9åäö])|[a-z0-9åäö]+', 'ig');
var translated = str.replace(re, function(m) {
var word = m.toLowerCase();
var trans = dict[word];
return trans === undefined ? word : trans;
});
console.log(translated);

Getting Rid of Extraneous Characters in a String-Javascript

I am loading data about NBA games from an API using Javascript, and I want to manipulate it but am having trouble. Each game is its own separate object, and is the data is returned like this:
Date: "Nov 7, 2014"
Opponent: "# Charlotte"
Result: "L"
Score: "122-119"
Spread: "+1.5"
Depending on whether the team is home or away, there is either a "#" or a "vs" in front of the name of the opponent for that particular game. I want to get rid of this, so that the "Opponent" key only has "Charlotte" as its value in the above example.
I've tried usinggameLog[i].Opponent = (gameLog[i].Opponent.split(" ").pop
to get rid of any characters before the space, but this ruins the data when there is a team name with a space in it like "New York" or "Los Angeles"
This takes the string, and creates a new substring starting at the index of the first white space. e.g.:
# New York = a new string starting after the #. -> New York
gameLog[i].Opponent = gameLog[i].Opponent.substr(gameLog[i].Opponent.indexOf(' ')+1);
I guess, something along these lines might help.
var home = "# Charlotte";
var opponent = "vs New York";
function parse(team){
// Case when it is a home team
if ( team.indexOf("#") === 0 ){
return team.replace("#","").trim();
// Away team
} else {
return team.replace("vs","").trim();
}
}
console.log( parse(home) );
console.log( parse(opponent) );
gameLog[i].Opponent = (gameLog[i].Opponent.split(" ").slice(1).join(" "));
Split based off space character
Slice off the first item in the array
Join the contents of the array back together with space.
You can use regular expressions to replace unwanted characters while looping over an array of objects.
for (var i = 0; i < arr.length; i++) {
arr[i].Opponent = arr[i].Opponent.replace(/#\s|vs\s/g, '');
}
Here's a jsbin
You need the substr() method:
var str = "# Charlotte";
var res = str.substr(2);
Result: Charlotte
Unless there is also a space after "vs", which is not clear.
Then you could use:
var str = "# Charlotte";
var res = str.substr(str.indexOf(' ')+1);

How to get abc from "abc def"?

"abc def"
"abcd efgh"
If I have a large string with a space that separates two substrings of varying length, what's the best way to extract each of the substrings from the larger string?
Because this is a string rather than an array, array syntax s[0] will only retrieve the first letter of the string ('a'), rather than the first substring.
Use the split method of the String object:
"abc def".split(' ')[0] // Returns "abc"
Works like this:
"string".split('separator') // Returns array
var arr = "abc def".split(" ");
document.write(arr[0]);
should work
Both above Answer's are right I am just putting it so that user can do some operation with every token. All you need to add a loop for that.
function splitStr(str){
var arr = str.split(" ");
for(i=0 ;i < arr.length ; i++){
//You will get a token here
// var token = arr[i];
// Do some thing with this token
}
}
One can return the array for any other operation in other function as
function splitStr(str){
var arr = str.split(" ");
return arr;
}

Categories

Resources