I understand that regex is a possibility, but I'd like to edit a lot of things at once. Minimalizing chaining. It just doesn't look to great in code.
for example,
Let's say the alphabet is jumbled up.
A would be E
B would be H
E would be D
How would I change ABE into EHD using a minimal amount of functions?
To be crystal clear, I have an object with this jumbled up alphabet.
TL;DR:
Best way to bulk-update letters in a string to their assigned counterparts?
You could write some logic where you would split the string into an array of characters and then compare the separate values using map() and replace when needed. Then join the array back to a string.
const original = "ABE";
const splitted = original.split("");
const replaced = splitted.map((letter) => {
if(letter === "A") return "E"
if(letter === "B") return "H"
if(letter === "E") return "D"
return letter
});
console.log(replaced.join(""));
The easiest would be to use a regular expression but also pair it with a replacer function:
const substitutions = {
"A": "E",
"B": "H",
"E": "D"
};
function transform(input) {
return input.replace(/./g, char => {
const sub = substitutions[char] ?? char;
return sub;
});
}
console.log(transform("HELLO WORLD!"));
console.log(transform("BEAUTIFUL!"));
console.log(transform("BOATS ARE EXCELLENT 👍"));
The regex /./g simply matches every single character and the replacer function then checks if it exists in substitutions and returns that. Or if it doesn't exist, it falls back to the same character thanks to the nullish coalescing operator (??).
This requires you to specify lowercase and uppercase characters explicitly in substitutions.
const substitutions = {
"a": "e",
"A": "E",
"b": "h",
"B": "H",
"e": "d",
"E": "D"
};
function transform(input) {
return input.replace(/./g, char => {
const sub = substitutions[char] ?? char;
return sub;
});
}
console.log(transform("Hello world!"));
console.log(transform("Beautiful!"));
console.log(transform("Boats Are Excellent 👍"));
If you always want the replacement to match the case (a -> e and A -> E) and do not want the extra entries in substitutions, then you can can check the case of the character and transform the replacement:
const substitutions = {
"A": "E",
"B": "H",
"E": "D"
};
function transform(input) {
return input.replace(/./g, char => {
const upperChar = char.toLocaleUpperCase();
if (!(upperChar in substitutions))
return char;
const isUpper = char === upperChar;
const sub = substitutions[upperChar];
if (isUpper)
return sub.toLocaleUpperCase();
return sub.toLocaleLowerCase();
});
}
console.log(transform("Hello world!"));
console.log(transform("Beautiful!"));
console.log(transform("Boats Are Excellent 👍"));
Related
So here's an example:
{
"part": "Intro",
"e": "------5/6------8\\6-|-------------------|-------------------",
"B": "-----------9-------|---------6p8---(6)-|-------------------",
"G": "--8----------------|---8h9-------------|--<8>--------------",
"D": "",
"A": "",
"E": "",
"endMsg": "Continue..."
}
Note: The double-slash will turn into one slash only upon render of text.
I want to get value from this object that is not empty. (So that could be from the e key or from the B key. As long it's not empty.)
Then I'm replacing that value using this expression here:
str.replace(/[0-9-. a-zA-Z // \ ~ ( ) < >]/g, '-');
It's for replacing the numbers, letters, and other characters into dashes.
I want to use that value with the dashes and pipe chars only to fill up the other keys inside the same object that are empty.
In the end, I want it to look something like this:
{
"part": "Intro",
"e": "------5/6------8\\6-|-------------------|-------------------",
"B": "-----------9-------|---------6p8---(6)-|-------------------",
"G": "--8----------------|---8h9-------------|--<8>--------------",
"D": "-------------------|-------------------|-------------------",
"A": "-------------------|-------------------|-------------------",
"E": "-------------------|-------------------|-------------------",
"endMsg": "Continue..."
}
I have no idea how to achieve this in code. Please help.
You can loop over each key value pair and replace the value if its empty. Be aware that a backslash is used for escaping a character. To fix this we first replace the backslashes with dashes and then replace the rest.
The regex could also be simplified to /[^-|]/g which means replace all symbols except - and |
const lines = {
"part": "Intro",
"e": "------5/6-----8\\6-|-------------------|-------------------",
"B": "-----------9-------|---------6p8---(6)-|-------------------",
"G": "--8----------------|---8h9-------------|--<8>--------------",
"D": "",
"A": "",
"E": "",
"endMsg": "Continue..."
};
const createFullLines = (lines, blacklist = ['part', 'endMsg']) => {
// Find a line that is not empty
const line = Object.entries(lines).find(([key, line]) => {
return !blacklist.includes(key) && line.trim();
});
// Exit if all lines are empty
if(!line) return lines;
// Destructure to get only value
const [_, filledLine] = line;
// Create new line with only dashes
const newLine = filledLine.replace(/[^-|]/g, '-');
// Update lines
for(const key in lines) {
lines[key] ||= newLine;
}
return lines;
}
const result = createFullLines(lines);
console.log(result);
You should just iterate between your object's keys like this:
// find first non-empty field, !! - conversion to boolean
let nonEmptyKey = Object.keys(obj).find(key => !!obj[key]);
for(let key of Object.keys(obj)) {
// check if value is empty
if(!obj[key]) {
obj[key] = obj[nonEmptyKey].replace(/[0-9-. a-zA-Z // \ ~ ( ) < >]/g, '-');
}
}
Also, you can simplify your regex to this:
// replace all symbols except - and |
str.replace(/[^-|]/g, '-');
I need to return a filtered string with "a1a" from the following function.
I've tried several regexes but nothing. On top of all, I can't use methods (part of the challenge).
let extractPassword = function(arr) {
let toString = "";
for (let i in arr) {
if ( arr[i] === /[A - Za - z0 -9]/) {
toString += arr[i];
}
console.log(toString);
}
};
extractPassword(["a", "-", "~", "1", "a", "/"]);
Any ideas?
Thank you.
Your code has a few problems.
Remove the spaces inside the regex. A-Z and A - Z do not mean the same thing. The first indicates you want to match any letter between A and Z inclusive. The latter indicates you want to match A, -, or Z.
Use the test(...) method on the regex object to determine whether the string matches the regular expression pattern. A string cannot ever be equal to the regex object.
The toString variable is a commonly used method. This makes your code a little less clear. I gave it a more appropriate name, extractedPw, which better denotes its purpose.
You are not returning anything from your method. The name "extract password" suggests it will return an extracted password.
let extractPassword = function(arr) {
let extractedPw = "";
for (let i in arr) {
if (/[A-Za-z0-9]/.test(arr[i])) {
extractedPw += arr[i];
}
console.log(extractedPw);
}
return extractedPw;
};
extractPassword(["a", "-", "~", "1", "a", "/"]);
So, you just want to take the characters that match your regex and join them?
let extractPassword = arr => arr.filter(v => v.match(/[A-Za-z0-9]/)).join('');
let pw = extractPassword(["a", "-", "~", "1", "a", "/"]);
console.log(pw);
If you mean filter and join are prohibited, then you can reinvent them trivially:
let extractPassword = arr => {
let r = '';
for (let v of arr)
if (v.match(/[A-Za-z0-9]/))
r += v;
return r;
};
let pw = extractPassword(["a", "-", "~", "1", "a", "/"]);
console.log(pw);
String === regular expression doesn't work.
Instead use RegExp.prototype.test()
More information here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test
Your code could look like this:
let extractPassword = function(arr) {
let toString = "";
const regex = /[A-Za-z0-9]/;
for (let i in arr) {
if (regex.test(arr[i])) {
toString += arr[i];
}
}
return toString;
};
console.log(extractPassword(["a", "-", "~", "1", "a", "/"]));
Create a function named extractPassword which takes an array of characters (which includes some trash characters) and returns a string with only valid characters (a - z, A - Z, 0 - 9).
I need a function in JavaScript that takes one string as input, replaces many substrings with their corresponding values, then returns the result. For example:
function findreplace(inputStr) {
const values = {"a": "A",
"B": "x",
"c": "C"};
// In this example, if inputStr is "abc", then outputStr should be "AbC".
return outputStr
}
I know how to individually find and replace, but I was wondering if there was an easy way to do this with many pairs of (case-sensitive) values at once.
Thank you!
Just iterate over values with the help of Object.entries(values):
function findreplace(inputStr) {
const values = {
"a": "A",
"B": "x",
"c": "C"
};
for (const [search, replace] of Object.entries(values)) {
inputStr = inputStr.replace(search, replace);
}
return inputStr;
}
console.log(findreplace("abc"));
You can join keys to build a regex and then replace accordingly
function findreplace(inputStr) {
let values = { "a": "A", "B": "x", "c": "C" };
let regex = new RegExp("\\b" + Object.keys(values).join('|') + "\\b", 'g')
return inputStr.replace(regex, (m) => values[m] )
}
console.log(findreplace('aBc'))
console.log(findreplace('AbC'))
console.log(findreplace('ABC'))
I want to replace each letter in more one word like this example:
if user typed #(*#$^ $^* by the code I want to change each letter to cinema man. Explaining more - I want to make a map like this:
"#" = "c";
"(" = "i";
"*" = "n";
"#" = "e";
"$" = "m";
"^" = "a";
How I can make that process with JavaScript?
If you're just wanting to map those specific characters, you can do something like this:
var myMap = {
"#": "c",
"(": "i",
"*": "n"
};
var string = "#(*";
var newLetters = string.split('').map(function(letter){
return myMap[letter];
});
newLetters.join('');
You just need to create an object to reference it's key-value pair.
Edit: Obviously you can fix this to work to your liking, just something I whipped up to illustrate the over all idea.
Create a object in order to store the mapping. Now parse the string and replace each word with its mapped work. Here is a working demo:
var mapping = {
"#": "c",
"(": "i",
"*": "n",
"#": "e",
"$": "m",
"^": "a"
};
var string = "#(*#$^ $^*";
var output = string.split("").map(function(el) {
if(mapping.hasOwnProperty(el))
return mapping[el];
return el;
}).join("");
alert(output);
Please consider this scenario:
I have a Key/Value variable like this:
var dict = {"78": "X",
"12": "G",
"18": "R",
"67": "U",
"68": "O",
"30": "P"}
I have a string that I want to check if there is a letter of my variable exist in my string. How I can do this?
Collect object key values and use them to create a regular expression. Then use .test(yourString):
var myStr = "Group";
new RegExp(Object.keys(dict).map(function (c) { return dict[c]; }).join("|"))
.test(myStr); // true
Another way is simply iterating the object:
var found = false;
for (var k in dict) {
if (myStr.indexOf(dict[k]) !== -1) {
found = true;
break;
}
}
if (found) {
// letter found
}
One possible approach:
var contains = Object.keys(dict).some(function(key) {
return someStr.indexOf(dict[key]) !== -1;
});
In other words, iterate over the collection, at each step checking whether or not the tested character present in your string (someStr). If it is, stops the iteration immediately (that's how Array.prototype.some works).
Another approach is building a character class regex, then using it against the string:
var pattern = RegExp('[' + Object.keys(dict).map(function(k) {
return dict[k];
}).join('') + ']');
var contains = pattern.test(someStr);
The second approach is slightly better if the tested strings usually do contain the characters from dict. It's also quite easy to augment this solution into case-insensitive search - just add 'i' string as a second param of RegExp call.
The caveat is that you'll have to escape the characters that will be considered meta within a string passed into RegExp constructor (backslash, for example). If there are no such characters in the dictionary, it's not a problem, though.
It can be done using the following:
str = "test";
isExists = false;
for(var key in dict){
isExists = str.indexOf(dict[key]) !== -1;
if(isExists)
break;
};
console.log(isExists);