Replace words with array map - javascript

I have this array
(2) ['beginning=beginner', 'leaves=leave']
and this string
its beginner in the sounds leave
which i have converted to an array
var words = text.split(' ');
i want to replace beginner with beginning and leave with leaves it can be any dynamic words but for now it has only two elements i can replace it within for loop. Is it possible with map method.
this.words.map((words, i) => console.log(words));
Note: Only first instance should get replaced.
Any Solution Thanks

does this correct with your question ?
const arrString = ["beginning=beginner", "leaves=leave", "sound=sounds"];
let string = "its beginner in the sounds leave";
arrString.forEach((mapString) => {
const stringArr = mapString.split("=");
string = string.replace(stringArr[1], stringArr[0]);
});
console.log("string", string);
// "its beginning in the sound leaves"

You can do it in without a nested loop too if you compromise with space.
Here is a solution which creates a mapping object for replacement values and uses array methods like map(),forEach(),join() and string method like split()
const arrString = ["beginning=beginner", "leaves=leave", "sound=sounds"];
let string1 = "its beginner in the sounds leave beginner";
const replaceObj = {};
const arrBreaks = arrString.forEach(x => {
let els = x.split("=");
replaceObj[els[1]] = els[0]; });
const ans = string1.split(' ').map((x) => {
if(x in replaceObj) { let val = replaceObj[x]; delete val; return val; }
return x;
}).join(' ');
console.log(ans);

Related

How split string into separate variables based on several characters in Java Script

There is a String variable that comes value like the following.
"COMPANY=10^INVOICE_ID=100021^"
I need to get this into two variables like Company and InvoieId.
What will be possible ways to do that JS?
Here is a dynamic way. You can grab any value from obj.
const str = "COMPANY=10^INVOICE_ID=100021^"
const obj = {}
const strArr = str.split('^')
strArr.forEach(str => {
const [key, value] = str.split('=')
obj[key] = value
})
const {COMPANY, INVOICE_ID } = obj
console.log(INVOICE_ID, COMPANY)
We can also do it via regular expression
Regex101 demo
let str = `COMPANY=10^INVOICE_ID=100021^`
let regex = /(\w+)=\d+/g
let match = regex.exec(str)
while(match){
console.log(match[1])
match = regex.exec(str)
}
If this code will be called more than once, let's create a function:
const parseInput = (input) => {
const [company, invoice_id] =
input.split("^")
.map(kv => kv.split("=")[1]);
return {
company,
invoice_id
};
}

JS array methods

I have a paragraph stored in a variable named story.
story = story text;
(example).
The first step in the project is to separate each word in the story variable and store it in an array named storyWords.
Easy enough, check.
Now it wants us to iterate through storyWords, filter out unnecessaryWords and store the new array in a variable named betterWords.
unnecessaryWords = ['extremely', 'literally', 'actually'];
Here is my code:
const betterWords = storyWords.filter(word => {
if(word !== unnecessaryWords)
return word;
});
What leads me to believe that this should work is based on this code:
const betterWords = storyWords.filter(word => {
if(word !== 'extremely')
if(word !== 'literally')
if(word !== 'actually')
return word;
})
What am I not understanding here?
If you want to exclude the entry as long as it matches any of the unnecessary words that is an array:
const unnecessaryWords = ['extremely', 'literally', 'actually'];
...then you can simply return !unnecessaryWords.includes(word), which means "if word is not included in the array of unnecessaryWords, we want to keep it":
const betterWords = storyWords.filter(word => !unnecessaryWords.includes(word));
Array.prototype.includes will return true when word matches any of the array members in unnecessaryWords.
Proof-of-concept:
const unnecessaryWords = ['extremely', 'literally', 'actually'];
const storyWords = ['Lorem', 'ipsum', 'extremely', 'dolor', 'sit', 'actually', 'amet'];
const betterWords = storyWords.filter(word => !unnecessaryWords.includes(word));
console.log(betterWords);
The following uses a regular expression and String#matchAll to match word character sequences following a word boundary. Array#filter is then used to filter out the unnecessary words.
const unnecessaryWords = ['extremely', 'literally', 'actually']
function betterWords(text) {
const words = [...text.matchAll(/\b\w+/gu)].flat()
return words.filter((w) => !unnecessaryWords.includes(w))
}
const text = 'literally the story text'
console.log(betterWords(text))
You could try two approaches. Using a Array.forEach() and Array.filter() like i demonstrated below.
// Just for Illustration, let's initialize a list representing storyWords
var storyWords = ['story','extremely', 'global','actually', 'javascript','c-sharp','literally'];
var unnecessaryWords = ['extremely', 'literally', 'actually'];
//First using simple loop
var betterWordsLooped = [];
storyWords.forEach((word)=>
{
if(!unnecessaryWords.includes(word))
{
betterWordsLooped.push(word);
}
});
console.log(betterWordsLooped);
//Secondly Using Filter
var betterWordsFiltered = storyWords.filter((word)=> !unnecessaryWords.includes(word));
console.log(betterWordsFiltered);
On this code:
!unnecessaryWords.includes(word))
we want to check if the value of variable word matches any of the items contained in the string array unnecessaryWords. Remember the pattern for using Array.propotype.includes() is someArray.includes(someVar) where someArray is a [] and someVar is a string variable whose value you want to match within someArray.

How to check if 2 strings separated by delimiters have matching word

Trying to check if 2 strings have matching word return true.
let 1st_string = chin, kore, span;
let 2nd_string = chin eng kore zulu
1st_string.split(',').indexOf(2nd_string) > -1
I tried above code but always returns false. I need to return true as 2_nd string contains 2 matching words from 1st_string.
Solved the names and values of the variables you can do the following
let first_string = 'chin, kore, span';
let second_string = 'chin eng kore zulu';
const array1 = first_string.split(',').map(string => string.trim());
const array2 = second_string.split(' ');
function exist(list1, list2) {
for (const element of list1) {
if (list2.includes(element)) {
return true;
}
}
return false;
}
const result = exist(array1, array2);
console.log(result);
1st_string is not a valid variable name
split the first string and use Array.some() to see if the second string has any of the words in the resulting array :
let string_1 = 'chin, kore, span';
let string_2 = 'chin eng kore zulu';
const check = (str1, str2) => {
return str1.split(',').some(word => str2.includes(word));
}
console.log(check(string_1, string_2))
I think your second string will also contain a comma in between the words if yes then it is easy to achieve.
you can split the string 1 and 2 with a comma as delimiter like this
let firstString = 1st_string.split(',');
let secondString = 2nd_string.split(',');
after doing you will get the firstString and secondString variable as array then you can iterate the first array and check for duplicate using includes methods
for (let i in firstString) {
if(secondString.includes(firstString[i])){
//you can do whatever you want after finding duplicate here;
}
}

How can I get the value from a string that has the values inside a square bracket []?

I have a string that comes to me like this: "[value1][value2]"
How can I get the values that are inside the square brackets?
NOTE: if the string is like this "[][value2]" the first bracket that has a space must return a "" to me...
I have been trying a lot of regex and split but none workd.
this is the last I tried:
var pattern = /[([^]]*)]/g;
var res = pattern.exec(datos[0].title);
Another one I tried is:
var res = datos[0].title.match(/^.*?[([^]]*)].*?[([^]]*)]/gm);
but none do what I need...
I'm trying to find a way "that does it all" a regex that gets anything inside the Square brackets (even white spaces)
As #HarryCutts stated, you don't need regex:
var x = "[value1][value2]";
console.log( x.slice(1,-1).split('][') );
You can try this regex and the brute force way to extract the contents.
var regex = /\[(.*?)\]/g;
var value = "[value1][value2][]";
var matches = value.match(regex);
var matchedValues = matches.map(match => {
return match.replace("[", "").replace("]", "");
}).join(" ");
console.log(matchedValues.toString())
You could just do this:
var str = "['value1']['value2']";
var value1 = str.split("]")[0].split("[")[1];
var value2 = str.split("]")[1].split("[")[1];
console.log(str);
console.log(value1);
console.log(value2);
You can easily expand it for more values.
const string = "[value1][value2]";
const removeBrackets = (stringWithBrackets) => {
return stringWithBrackets.split("][").map(s => s = s.replace(/\[*\]*/g, ""));
};
const [value1, value2] = removeBrackets(string);
console.log(value1, value2);
const getItems = (fullItemsString) => {
let items = fullItemsString.replace(/\[/g, "").split("]");
items.pop()
return items;
}
Using:
let items = getItems("[2][][34][1]");
result: [ '2', '', '34', '1' ]

In javascript, Find an item in an array that contains a string and then return that item

I have an array of strings.
I want to search in that array for and string that contains a specific string.
If it's found, return that string WITHOUT the bit of the string we looked for.
So, the array has three words. "Strawbery", "Lime", "Word:Word Word"
I want to search in that array and find the full string that has "Word:" in it and return "Word Word"
So far I've tried several different solutions to no avail. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes looks promising, but I'm lost. Any suggestions?
Here's what I've been trying so far:
var arrayName = ['Strawberry', 'Lime', 'Word: Word Word']
function arrayContains('Word:', arrayName) {
return (arrayName.indexOf('Word:') > -1);
}
You can use find to search the array. And use replace to remove the word.
This code will return the value of the first element only.
let arr = ["Strawbery", "Lime", "Word:Word Word"];
let search = "Word:";
let result = (arr.find(e => e.includes(search)) || "").replace(search, '');
console.log(result);
If there are multiple search results, you can use filter and map
let arr = ["Strawbery", "Word:Lime", "Word:Word Word"];
let search = "Word:";
let result = arr.filter(e => e.includes(search)).map(e => e.replace(search, ''));
console.log( result );
Use .map:
words_array = ["Strawbery", "Lime", "Word:Word Word"]
function get_word(words_array, search_word) {
res = '';
words_array.map(function(word) {
if(word.includes(search_word)) {
res = word.replace(search_word, '')
}
})
return(res)
}
Usage:
res = get_word(words_array, 'Word:')
alert(res) // returns "Word Word"

Categories