How we can ignore some space in JavaScript? - javascript

I did this code :
var fs = require('fs');
var str = fs.readFileSync('input.txt', 'utf8');
str.split(/\s+/).forEach(function (s) {
return console.log(
s === 'bob'
? 'boy'
: s === 'alicia'
? 'girl'
: s === 'cookie'
? 'dog'
: 'unknown');
});
But in my input file there are some space, and I don't want my code to take it into account. My input file is :
cat
bob
alicia
shirley
cookie
thomas
rat`
So how can I code, to ignore the space in my input file please ?

First of all if you'd console.log(str.split(/\s+/)) you'll get
[ 'cat', 'bob', 'alicia', 'shirley', 'cookie', 'thomas', 'rat`' ]
so as everyone has already said /\s+/ will in fact remove the spaces
#JuanCaicedo your solution doesn't work well sorry, I tried and between cookie and thomas there are space, and the code write unknown. The result is unknown boy girl unknown dog unknown unknown unknown so after rat the code take care about the space
the output you're seeing is correct, according to your logic
s === 'bob'
? 'boy'
: s === 'alicia'
? 'girl'
: s === 'cookie'
? 'dog'
: 'unknown');
If the string doesn't equal bob or alicia or cookie it will output unknown therefore
cat = unknown
bob = boy
alicia = girl
shirley = unknown
cookie = dog
thomas = unknown
rat` = unknown

Please look at the code below
function removeEmptyLines(str) {
const arrayOfLines = str.split("\n"); // Remove empty lines from the string which leaves "" in the returned array
const filtered = arrayOfLines.filter(line => line !== ""); // filter the array and remove all the empty strings
const joined = filtered.join(" "); // form a single string
return joined; // return filtered array
}

Related

Partial String Match - Dynamic Strings

For certain dynamic strings like:
covid-19 testing status upto may 05,2021
covid-19 testing status upto may 04,2021
covid-19 testing status upto may 01,2021
....
covid-19 testing status upto {{date}}
and others like:
Jack and Jones are friends
Jack and JC are friends
Jack and Irani are friends
.....
Jack and {{friend-name}} are friends
I want to match the incoming string like:
covid-19 testing status upto may 01,2021
with
covid-19 testing status upto {{date}}
and if there is a match, I want to extract the value of date.
Similarly, for an incoming string like
Jack and JC are friends
I want to match with
Jack and {{friend-name}} are friends
and extract JC or the friend-name. How could I do this?
I am trying to create a setup where dynamic strings like these, can be merged into one. There could be thousands of incoming strings that I want to match against the existing patterns.
INCOMING_STRINGS -------EXISTING-PATTERNS----->
[
covid-19 testing status upto {{date}},
Jack and {{friend-name}} are friends,
....
] ---> FIND THE PATTERN AND EXTRACT THE DYNAMIC VALUE
EDIT
It is not guaranteed that the pattern will always exist in the incoming strings.
It's very easy to use regex for the second of your examples. If you use a capturing group for the "friend name" part you can extract that with ease:
const re = /Jack and ([a-zA-Z]+) are friends/
const inputs = ["Jack and Jones are friends",
"Jack and JC are friends",
"Jack and Irani are friends",
"Bob and John are friends"] // last one wont match
for(let i=0;i<inputs.length;i++){
const match = inputs[i].match(re);
if(match)
console.log("friend=",match[1]);
else
console.log("No match for the string:", inputs[i])
}
The first example is slightly hardeer, but only because the regex is more difficult to write. Assuming the format is always "short month name 2 digit day comma 4 digit year" it is doable
const re = /covid-19 testing status upto ((jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec) (0?[1-9]|[12][0-9]|3[01]),\d{4})/
const inputs = ["covid-19 testing status upto may 05,2021",
"covid-19 testing status upto may 04,2021",
"covid-19 testing status upto may 01,2021",
"covid-19 testing status upto 01/01/2020"] // wrong date format
for(let i=0;i<inputs.length;i++){
const match = inputs[i].match(re);
if(match)
console.log("date=",match[1]);
else
console.log("No match for the string:", inputs[i])
}
It's fairly unclear to me what your actual inputs and outputs should be. Here's an attempt that guesses at that. With inputs like
[{
sample: 'covid-19 testing status upto may 05,2021',
extract: 'may 05,2021',
propName: 'date'
}, {
sample: 'Jack and Jones are friends',
extract: 'Jones',
propName: 'friend-name'
}]
we generate a function which can be used like this:
mySubs ('Jack and William are friends')
//=> {"friend-name": "William"}
or
(mySubs ('covid-19 testing status upto apr 30,2021')
//=> {"date": "apr 30,2021"}
or
mySubs ('Jack and Jessica are friends who dicsussed covid-19 testing status upto apr 27,2021')
//=> {"date": "apr 27,2021", "friend-name": "Jessica"}
and which would yield an empty object if nothing matched.
We do this by dynamically generating regular expressions for our samples, ones which will capture the substitutions made:
const regEscape = (s) =>
s .replace (/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
const makeTester = ({sample, extract, propName}) => ({
regex: new RegExp (
regEscape (sample .slice (0, sample .indexOf (extract))) +
'(.+)' +
regEscape (sample .slice (sample .indexOf (extract) + extract .length))
),
propName
})
const substitutes = (configs, testers = configs .map (makeTester)) => (sentence) =>
Object.assign( ...testers .flatMap (({regex, propName}) => {
const match = sentence .match (regex)
return (match)
? {[propName]: match[1]}
: {}
}))
const configs = [{
sample: 'covid-19 testing status upto may 05,2021',
extract: 'may 05,2021',
propName: 'date'
}, {
sample: 'Jack and Jones are friends',
extract: 'Jones',
propName: 'friend-name'
}]
const mySubs = substitutes (configs)
console .log (mySubs ('Jack and William are friends'))
console .log (mySubs ('covid-19 testing status upto apr 30,2021'))
console .log (mySubs ('Jack and Jessica are friends who dicsussed covid-19 testing status upto apr 27,2021'))
console .log (mySubs ('Some random string that does not match'))
.as-console-wrapper {max-height: 100% !important; top: 0}
If you needed to also report what templates matched, you could add a name to each template, and then carry the results through the two main functions to give results like this:
{"covid": {"date": "apr 27,2021"}, "friends": {"friend-name": "Jessica"}}
It's only slightly more complex:
const regEscape = (s) =>
s .replace (/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
const makeTester = ({name, sample, extract, propName}) => ({
regex: new RegExp (
regEscape (sample .slice (0, sample .indexOf (extract))) +
'(.+)' +
regEscape (sample .slice (sample .indexOf (extract) + extract .length))
),
propName,
name
})
const substitutes = (configs, testers = configs.map(makeTester)) => (sentence) =>
Object.assign( ...testers .flatMap (({name, regex, propName}) => {
const match = sentence .match (regex)
return (match)
? {[name]: {[propName]: match[1]}}
: {}
}))
const configs = [{
name: 'covid',
sample: 'covid-19 testing status upto may 05,2021',
extract: 'may 05,2021',
propName: 'date'
}, {
name: 'friends',
sample: 'Jack and Jones are friends',
extract: 'Jones',
propName: 'friend-name'
}]
const mySubs = substitutes (configs)
console .log (mySubs ('Jack and William are friends'))
console .log (mySubs ('covid-19 testing status upto apr 30,2021'))
console .log (mySubs ('Jack and Jessica are friends who dicsussed covid-19 testing status upto apr 27,2021'))
console .log (mySubs ('Some random string that does not match'))
Either way, this has some limitations. It's hard to figure out what to do if the templates overlap in odd ways, etc. It's also possible that you want to match only complete sentences, and my examples of double-matching won't make sense. If so, you can just prepend a '^' and append a '$' to the string passed to new RegExp.
Again, this is a guess at your requirements. The important thing here is that you might be able to dynamically generate regexes to use.

Discord.js command check empty space only once

when someone inputs a command !add James Bond;Michael B Jordan the argument takes it as "James"arg[0], "Bond;Michale"args[1], "B"args[2], "Jordan"args[3]. Any way i can make it so that it only counts the empty space after the "!add" and then splits using ";" ?. Final answer would be "James Bond"args[0], "Michael B Jordan"args[1].
client.on('message',async(message)=>{
if(!message.content.startsWith(prefix2)||message.author.bot)return;
const args2=message.content.slice(prefix.length).trim().split(/ +/);
const command= args2.shift().toLowerCase();
This is what i tried but it doesnt seem to work
if(!message.content.startsWith(prefix2)||message.author.bot)return;
const args2=message.content.slice(prefix.length).trim().split(/ {1}[;]+/);
const command= args2.shift().toLowerCase();
Thanks
Since we know !add will always takeup 5 characters of the string, we can crop out those 5 using String.prototype.slice().
This will then return 'James Bond;Michael B Jordan', which we can ofcourse split by ; to return each name in it's own array element.
client.on('message', async(message) => {
// message.content = '!add James Bond;Michael B Jordan'
const rawContent = message.content.slice(5);
const celebrityArguments = rawContent.split(';');
console.log(celebrityArguments);
// ["James Bond", "Michael B Jordan"]
})

TinyMce 4 util.i18n.translate() usage

I try since hours and using the (very less helpful API documentation :S) to get translation for my plugin working.
tinymce.translate('Cut'); // returns Ausschneiden for de
So far, so good.
tinymce.translate('myplugin.test'); // returns myplugin.test
I checked tinymce.i18n.data and can see through inspector that it contains the data I added with
tinymce.addI18n('de.myplugin', {
"test": 'test label'
});
before.
This is probably something stupid but I can not figure it out.
UPDATE
I now add my own functionality to do it manually as I can not figure it out how to do it:
plugin_translate = function(val) {
return (eval('tinymce.i18n.data.' + tinymce.settings.language + '.' + val) != undefined)
? eval('tinymce.i18n.data.' + tinymce.settings.language + '.' + val)
: val;
}
And my plugin/langs/de.js looks like this
tinymce.addI18n('de', { 'plugin': { "title" : 'Titel' }});
This doesn't look right but at the moment it works until someone enlighten me.
Translations are registered using tinymce.addI18n(langCode, translationMap) or tinymce.util.I18n.add(langCode, translationMap).
The first parameter is a language code like "en", "en_US" or "de". This should be the same value used for the language init property. Note that you should not include the plugin prefix here.
The second parameter is a map of translation-key to translation pairs. The translations can take positional arguments like {0} and {1}. You should prefix your keys with your plugin name to avoid naming clashes. For example:
{
"myplugin.test": "test label",
"myplugin.greeting": "Hello {0}, you are welcome"
}
So combining all those parts together you might register English and German translations like:
tinymce.addI18n("en", {
"myplugin.title": "My Plugin",
"myplugin.greeting": "Hello {0}, you are welcome"
});
tinymce.addI18n("de", {
"myplugin.title": "Mein Plugin",
"myplugin.greeting": "Hallo {0}, du bist willkommen"
});
Then to use the translation call tinymce.translate(translationKey) which returns the translated string. For a string without arguments you can just pass the same key you used in the map. For example:
var title = tinymce.translate("myplugin.title");
If your translation has parameters you have to wrap the key up in an array. For example:
var name = getName(); // get the name from the user
var greeting = tinymce.translate(["myplugin.greeting", name]);
If for some reason you need to override the translation you can provide an object with a raw string. For example:
var name = getName(); // get the name from the user
var key = name === "James" ? {"raw": "Go away!"} : ["myplugin.greeting", name];
var greeting = tinymce.translate(key);

Loop through a string to find text between character sets

I am trying to create a JavaScript function which would extract pre-defined variables from a string. Within the string, these variables will be nested within the "<>" character set.
For example:
the string which is typed by the user could be: I am <me> , my age is <myage>
which would then render the text: I am Joe Bloggs , my age is 21 (given the two user defined variables 'me' and 'myage')
I have begun to use the split funciton, but this is not going well.
function parse_String(theString) {
var varSplit = theString.split("<");
};
Is there an elegant solution, either using javascript or RegEx?
You seem to look for a 'templating' function. If you format the initial string like this 'I am {0}, my age is {1}', you could use this method:
function stringFormat() {
var args = [].slice.call(arguments);
return this.replace(/(\{\d+\})/g, function(a) {
return args[ +(a.split(/[{}]/)[1]) || 0 ];
});
};
// usage
stringFormat.call('I am {0}, my age is {1}','Joe Bloggs','21');
//=> I am Joe Bloggs, my age is 21
You could add the method to String.prototype:
String.prototype.Format = stringFormat;
// usage
'I am {0}, my age is {1}'.Format('Joe Bloggs','21');
You can use
var result = theString.substring(theString.indexOf('<')+1, theString.indexOf('>'))
You can simple do a replace function. I assume you want to replace the predifined places with your own variables.
function parse(string, data) {
$.each(data, function (v, k) {
string = string.replace('<'+k+'>', v);
});
return string;
}
Example
parse("<me> is <age> years old", {me:'Han', age:22});
output: Han is 22 years old

Format long string into JSON

I have this string that I get from an outside data source. It looks like this:
var myString = "Worker Management System :
Your request has been submitted
________________________________________
Your Account User Info:
Name : Doe, John, A
ID : JDOE123
Email :
Title : Worker
BusinessUnit : BARN
Department : PIGS
EmployeeID :
SupervisorName : Doe, Jane, B
HireDate : 02/22/2002
Role : Feed Pigs;
ManagerEmail : JaneDoe#mail.com
City : New York
State : NY
ZipCode : 12345
Phone : --
"
I'd like to parse this into a JSON (or something that i can work with) so that I can call maybe myString.Name and have it return Doe, John, A.
Is this possible? It's not an option for my to modify the way I get this string, I'm just trying to format it so I can easily extract the data from it.
I've looked into Douglas Crockford's JSON.parse, but that doesn't do me any good if my string isn't already properly formatted.
String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g, '');};
function my_string_to_object(myString)
{
var tmp = myString.split('Your Account User Info: ',2);
var tmp = tmp[1].split("\n");
var obj = {};
for(var k=0;k<tmp.length;k++) {
var line = tmp[k].split(' : ');
if(typeof(line[1]) != 'undefined') {
obj[ line[0].trim() ] = line[1].trim();
}
}
return obj;
}

Categories