replace characters in a string using an associative array mapping - javascript

I have an associative array/object such at this:
mymap = {'e':'f', 'l':'g'};
And I want to replace all matching characters in a string using the above as a simple cypher, but only replacing existing characters. As an example,
input = "hello world";
output = input.map(mymap); //how can I do this?
//output is "hfggo worgd"
Balancing performance (for large input) and code size are of interest.
My application is replacing unicode characters with latex strings using this map, but I'm happy to stick with the more general question.

The following works:
mymap = {'e':'f', 'l':'g'};
var replacechars = function(c){
return mymap[c] || c;
};
input = "hello world";
output = input.split('').map(replacechars).join('');
although having to split and then join the input seems quite round-about, particularly if this is applied to a wall of text.

Another way would be loop over the object properties and use regex for each replacement:
var input = 'hello world';
var output = '';
for (var prop in mymap) {
if (mymap.hasOwnProperty(prop)) {
var re = new RegExp(prop, 'g');
output = input.replace(re, mymap[prop]);
}
}

Related

JS turn a multi-line string into an array (each item= a line)

For example, I have:
var str = "Hello
World"
I'm expecting an array like that : array["Hello", "World"]
I looked for a method that does that but nothing, I tried to make a loop but I don't know on what I should base my loop? From my knowledge there's not a .length property for the amount of lines in a string...
Use the split function:
var str = `Hello
World`;
var splittedArray = str.split(/\r?\n/);
console.log(splittedArray)
First thing is that the input string is not valid. It should be enclosed by backtick not with a quotes and then you can replace the new line break with the space and then split it to convert into an array.
Live Demo :
var str = `Hello
World`;
const replacedStr = str.replace(/\n/g, " ")
console.log(replacedStr.split(' '));

Cant make regex work to remove the first white space character

I have the following div:
<div data-test="([1] Hello World), ([2] Foo Bar)"></div>
Now what I am trying to do is to find the cleanest way to break the string into the following pieces:
array ["1", "Hello World", "2", "Foo Bar"];
How can I achieve this the proper and fast way?
I managed to get close but my solution seems somewhat ugly and doesnt work as expected.
var el = document.getElementsByTagName("div")[0];
data = el.getAttribute('data-test');
list = data.replace(/[([,]/g, '').split(/[\]\)]/);
for(str of list) {
str = str.trim();
}
I still get the spaces at the start of each string. I dont really want to use trim or anything similar. I tried to add a whitespace character to my regex s/ but that was a bad idea too.
The below function should work.
function strToArr(str) {
var arr = [];
var parts = str.split(', ');
parts.forEach(part => {
var digit = part.match(/(\d+)/g)[0];
var string = part.match(/(\b[a-zA-Z\s]+)/g)[0];
arr.push(digit, string);
});
return arr;
}
var text = '([1] Hello World), ([2] Foo Bar)';
var textReplaced = text.replace(/\(\[([^\]])\]\s([^)]+)\)/g, '$1, $2');
var array = textReplaced.split(', ');
console.log(array);
Without any cycle.
You can try the following regular expression:
list = data.replace(/^\(\[|\)$/g, '').split(/\] |\), \(\[|\] /);
Two steps:
remove the heading "(["and tailing ")"
split the string into the parts you want with the delimiter symbols
Suppose the format of the string is fixed.

using regex to return new filename

Trying to get a filename and have it return a string.
try to turn:
plate-71-winter-hawk-final.jpg
into:
winter hawk final
where plate might also be uppercase. Here is what I have so far, doesn't seem to work
var theRegEx = new RegExp('[Plate|plate]-\d+-(.*).jpg');
var theString = "plate-71-winter-hawk-final.jpg"
var newString = theString.replace(theRegEx, theString);
newString;
Unfortunately, the "Rule #1" doesn't offer a better way:
var newString = theString.replace(/^[Pp]late-\d+-(.*)\.jpg$/, '$1')
.replace(/-/g, ' ');
Take care when you use a string with the object syntax to escape backslahes:
var theRegEx = new RegExp('^[Pp]late-\\d+-(.*)\\.jpg$');
Note that a character class is only a set of characters, you can't use it to put substrings and special regex characters loose their meaning inside it. [Plate|plate] is the same thing than [Pplate|]
You can write it like this too (without string):
var theRegEx = new RegExp(/^[Pp]late-\d+-(.*)\.jpg$/);
Try following script. It's not dependent on length of string as long as it follows standard pattern:
var data = "plate-71-winter-hawk-final.jpg";
var rx = /(?:plate\-\d+\-)(.*)(?=\.)/i;
var match = rx.exec(data);
if(match != null){
data = match[1];
data = data.replace(/\-/g, ' ');
}
console.log(data);
It will print:
winter hawk final

Get words from a string pattern in Javascript

I am trying to get words from a string dynamically using a pattern. The pattern and input look something like this
var pattern = "hello this is %var% using %var%";
var input = "hello this is nick using javascript";
Now I want to be able to have an array of the variables like this
["nick", "javascript"]
This should do it:
var pattern = "hello this is %var% using %var%";
var input = "hello this is nick using javascript";
var re = new RegExp(pattern.replace(/%var%/g, '([a-z]+)'));
var matches = re.exec(input).slice(1); // <-- ["nick", "javascript"]
The variable re is a RegExp whose pattern is the pattern variable with each instance of %var% replaced with a capturing group of lower case letters (extend if necessary).
matches is then the result of the re regex executed on the input string with the first element removed (which will be the full matching string).
var pattern = "hello this is %var% using %var%";
var input = "hello this is nick using javascript";
var outputArr = [];
pattern.split(" ").forEach(function (e, i){
e === "%var%" ? outputArr.push(input.split(" ")[i]) : "";
});
outputArr is the desired array.

How do I split this string with JavaScript?

Javascript:
var string = '(37.961523, -79.40918)';
//remove brackets: replace or regex? + remove whitespaces
array = string.split(',');
var split_1 = array[0];
var split_2 = array[1];
Output:
var split_1 = '37.961523';
var split_2 = '-79.40918';
Should I just use string.replace('(', '').replace(')', '').replace(/\s/g, ''); or RegEx?
Use
string.slice(1, -1).split(", ");
You can use a regex to extract both numbers at once.
var string = '(37.961523, -79.40918)';
var matches = string.match(/-?\d*\.\d*/g);
You would probably like to use regular expressions in a case like this:
str.match(/-?\d+(\.\d+)?/g); // [ '37.961523', '-79.40918' ]
EDIT Fixed to address issue pointed out in comment below
Here is another approach:
If the () were [] you would have valid JSON. So what you could do is either change the code that is generating the coordinates to produce [] instead of (), or replace them with:
str = str.replace('(', '[').replace(')', ']')
Then you can use JSON.parse (also available as external library) to create an array containing these coordinates, already parsed as numbers:
var coordinates = JSON.parse(str);

Categories