TinyMce 4 util.i18n.translate() usage - javascript

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);

Related

Get slug value from parameter using JavaScript

I have a url with format like this:
http://www.test.com/document/navigate/{{project_id}}/{{note_id}}
the value within {{}} will be filled with integer, like this for example
http://www.test.com/document/navigate/1/3
http://www.test.com/document/navigate/7/2
http://www.test.com/document/navigate/3
the value for note_id in the url is not mandatory, but i need to retrieve both for the project_id and note_id. how can i achieve that?
You can use a regular expression: http[s]?:\/\/www.test.com\/document\/navigate\/([\d]+)[\/]?([\d]+)?[\/]?.
Essentially it is laying out the protocol, hostname/domain, and the part of the path that we know. Then there are two capturing groups - the project ID and the note ID (optional).
You could use it like so:
const url = 'http://www.test.com/document/navigate/1/3';
const parts = url.match(/http[s]?:\/\/www.test.com\/document\/navigate\/([\d]+)[\/]?([\d]+)?/);
console.log(parts[0]); // "http://www.test.com/document/navigate/1/3" <- full match
console.log(parts[1]); // "1" <- first group
console.log(parts[2]); // "3" <- second group, which will be undefined if left off
Note: this may not be a foolproof answer. I recommend trying out many other potential variations. Also be aware that this returns strings, so you may have to parseInt() or something if you want real numbers.
Here is a Regexr showing you how this works (this is how I mess around until I get it right).
One way you can make use of the part navigate/ like the following way:
var url1 = 'http://www.test.com/document/navigate/1/3';
var url2 = 'http://www.test.com/document/navigate/7/2';
var url3 = 'http://www.test.com/document/navigate/3';
function getValue(url){
var arr = url.match(/navigate\/([^ ]*)/);
arr = arr[arr.length - 1].split('/');
if(arr.length == 1)
return { project_id: +arr[0] };
else if(arr.length == 2)
return { project_id: +arr[0], note_id: +arr[1] };
else
return 'invalid';
}
console.log(getValue(url1));
console.log(getValue(url2));
console.log(getValue(url3));

Regex split string and check if string is of type

Aanval op Vlemis (499|453) C44
This is what the string looks like. Though it's actually like this: "Aanval op variable (variable) variable
What I want to do is 1: get the coordinates (I already have this), 2 get Vlemis (first variable), get C44 (third variable) and check to see if the string is of this type.
My code:
$("#commands_table tr.nowrap").each(function(){
var text = $(this).find("input[id*='editInput']").val();
var attackername= text.match(/(?=op)[\s|\w]*(?=\()/);
var coordinates = text.match(/\(\d{1,3}\|\d{1,3}\)/);
});
Coordinates works, attackername however doesn't.
Html:
<span id="labelText[6]">Aanval op Vlemis (499|453) C44</span>
You should use one regex to take everything :
var parts = text.match(/(\w+)\s*\((\d+)\|(\d+)\)\s*(\w+)/).slice(1);
This builds
["Vlemis", "499", "453", "C44"]
If you're not sure the string is valid, test like this :
var parts = text.match(/(\w+)\s*\((\d+)\|(\d+)\)\s*(\w+)/);
if (parts) {
parts = parts.slice(1);
// do things with parts
} else {
// no match, yell at the user
}

ExtJS 4.1.1: Evaluating a field in a grid

I'm struggling with a ExtJS 4.1.1 grid that has editable cells (CellEditing plugin).
A person should be able to type a mathematic formula into the cell and it should generate the result into the field's value. For example: If a user types (320*10)/4 the return should be 800. Or similar if the user types (320m*10cm)/4 the function should strip the non-mathematical characters from the formula and then calculate it.
I was looking to replace (or match) with a RegExp, but I cannot seem to get it to work. It keeps returning NaN and when I do console.log(e.value); it returns only the originalValue and not the value that I need.
I don't have much code to attach:
onGridValidateEdit : function(editor,e,opts) {
var str = e.value.toString();
console.log(str);
var strCalc = str.match(/0-9+-*\/()/g);
console.log(strCalc);
var numCalc = Number(eval(strCalc));
console.log(numCalc);
return numCalc;
},
Which returns: str=321 strCalc=null numCalc=0 when I type 321*2.
Any help appreciated,
GR.
Update:
Based on input by Paul Schroeder, I created this:
onGridValidateEdit : function(editor,e,opts) {
var str = e.record.get(e.field).toString();
var strCalc = str.replace(/[^0-9+*-/()]/g, "");
var numCalc = Number(eval(strCalc));
console.log(typeof numCalc);
console.log(numCalc);
return numCalc;
},
Which calculates the number, but I am unable to print it back to the grid itself. It shows up as "NaN" even though in console it shows typeof=number and value=800.
Final code:
Here's the final code that worked:
onGridValidateEdit : function(editor,e,opts) {
var fldName = e.field;
var str = e.record.get(fldName).toString();
var strCalc = str.replace(/[^0-9+*-/()]/g, "");
var numCalc = Number(eval(strCalc));
e.record.set(fldName,numCalc);
},
Lets break this code down.
onGridValidateEdit : function(editor,e,opts) {
var str = e.value.toString();
What listener is this code being used in? This is very important for us to know, here's how I set up my listeners in the plugin:
listeners: {
edit: function(editor, e){
var record = e.record;
var str = record.get("your data_index of the value");
}
}
Setting it up this way works for me, So lets move on to:
var strCalc = str.match(/0-9+-*\/()/g);
console.log(strCalc);
at which point strCalc=null, this is also correct. str.match returns null because your regex does not match anything in the string. What I think you want to do instead is this:
var strCalc = str.replace(/[^0-9+*-]/g, "");
console.log(strCalc);
This changes it to replace all characters in the string that aren't your equation operators and numbers. After that I think it should work for whole numbers. I think that you may actually want decimal numbers too, but I can't think of the regex for that off the top of my head (the . needs to be escaped somehow), but it should be simple enough to find in a google search.

Can I 'match' values in 2 arrays and then use the subsequent 'matched' value?

I'm trying to achieve the following though with my intermediate JavaScript skills I'm not sure if this is possible.
This is related in part to this question.
Now I have 2 arrays
a) Has the various language in (e.g. "en-GB", "fr", "de" etc)
b) Has a suffix of a URL based on the browser language above (e.g. "fr/","de/","uk/")
What I am trying to achieve is:
1) User hits a page, browser detects which browser it is using from the array (a)
2) Depending on what the browser is based on (a), it then searches through (b) and if they match, e.g. if the language is "fr" it will use the suffix "fr/" from the array in (b).
3) It will then add this suffix to a top level domain (which is always constant)
Is this even possible to achieve (I'm sure it is)? Can it be done purely via JavaScript (or JQuery)? How would I go about doing this?
Here's some of the code I have so far:
var IAB_Array = new Array("de-at","nl-be","fr-be","da","de","hu","en-ie","ga","es","fr","it","nl","no","pl","en","en-GB","en-US","en-gb","en-us"); //language array
var IAB_suffix = new Array("at/","be-nl/","be-fr","den/","de/","hu/","ie/","es/","fr/","it/","nl/","nor/","pl/","uk/"); //URL suffix Array
var IAB_lang = "en-GB"; //default language
var IAB_link = "http://www.mysitegoeshere/";
if(navigator.browserLanguage) IAB_lang = navigator.browserLanguage; //change lang if detection supported
if(window.navigator.language) IAB_lang = window.navigator.language; //change lang if detection supported
function IAB_Lang_detect () { //execute search
for (var i=0;i<IAB_Array.length;i++) {
if(IAB_Array[i]==IAB_lang) {
document.write(IAB_Array[i]); //output matched array value
}
}
return false;
}
var IAB_URL = ""+IAB_link+IAB_suffix[1]+""; //this is the resulting URL
document.write(IAB_URL);
IAB_Lang_detect ();
I hope someone can help as I'm a little confused! It's more so the matching the values from the 2 arrays and then subsequently selecting the correct suffix that I'm having trouble with.
Thanks
(function () {
"use strict";
var lang_map = {
"de-at": "at/",
"nl-be": "be-nl/",
"fr-be": "be-fr",
"da": "den/",
"de": "de/",
"hu": "hu/",
"en-ie": "ie/",
"ga": "ie/",
"es": "es/",
"fr": "fr/",
"it": "it/",
"nl": "nl/",
"no": "nor/",
"pl": "pl/",
"en": "uk/",
"en-GB": "uk/",
"en-US": "uk/",
"en-gb": "uk/",
"en-us": "uk/"
},
lang = (navigator && navigator.browserLanguage) || (window.navigator && window.navigator.language) || "en-GB";
window.location = "http://www.mysitegoeshere/" + lang_map[lang];
}());
I'd do it differently and use an object:
var IAB_Object = { "it-It": "it/", "en-Gb": "en/" ....}
if(IAB_Object.hasOwnProperty(IAB_lang)){
//you have a match, the suffix is
var suffix = IAB_Object[IAB_lang];
}else{
//you don't have a match use a standard language
}
I probably wouldn't use arrays for this at all. You can use an object:
var IABInfo = {
"de-at": "at/",
"ln-be": "be-nl/",
// ...and so on
};
Then index directly into that object:
var value = IABInfo[IABLang]; // Where IABLang contains a string, like "de-at"
So:
var suffix = IABInfo[IABLang];
if (suffix) { // Did we have it?
document.write(suffix);
}
This works because all JavaScript objects are free-form key/value maps. Here's a simpler example:
var lifeTheUniverseAndEverything = {
answer: 42,
question: "?"
};
You can look up a property either using dotted notation with a literal, or by using square bracket ([]) notation with a string. So all four of these output exactly the same thing:
// 1. Dotted notation with a literal:
console.log("The answer is " + lifeTheUniverseAndEverything.answer);
// 2. Bracketed notation with a string
console.log("The answer is " + lifeTheUniverseAndEverything["answer"]);
// 3. The string needn't be a literal, it can come from a variable...
var name = "answer";
console.log("The answer is " + lifeTheUniverseAndEverything[name]);
// 4. ...or indeed any expression:
console.log("The answer is " + lifeTheUniverseAndEverything["a" + "n" + "swer"]);
So by making your IAB info a map in an object literal, you can make it much easier to look things up: Just use bracketed notation with the desired language code.

Javascript Regular Expression to attempt to split name into Title/First Name(s)/Last Name

I want to try and detect the different parts of a person's name in Javascript, and cut them out so that I can pass them onto something else.
Names can appear in any format - for example:-
miss victoria m j laing
Miss Victoria C J Long
Bob Smith
Fred
Mr Davis
I want to try and write something simple, that'll do it's best to guess these and get them right 80% of the time or so (We have some extremely dodgy data)
I'm thinking of something along the lines of using a regex to check whether it has a prefix, then branch off to two places as to whether it has
/^(Dr|Mr|Mrs|Miss|Master|etc).? /
And then cutting the rest of it out using something like
/(\w+ )+(\w+)/
To match last name and other names. Though, I'm unsure on my greedy/ungreedy options here, and whether I can do soemthing to shortcut having all the different paths that might be available. Basically, hoping to find something simple, that does the job in a nice way.
It's also got to be written in Javascript, due to the limitations of the ETL tool I'm using.
Why not split() and just check the resulting parts:
// Split on each space character
var name = "Miss Victoria C J Long".split(" ");
// Check the first part for a title/prefix
if (/^(?:Dr|Mr|Mrs|Miss|Master|etc)\.?$/.test(name[0])) {
name.shift();
}
// Now you can access each part of the name as an array
console.log(name);
//-> Victoria,C,J,Long
Working Demo: http://jsfiddle.net/AndyE/p9ra4/
Of course, this won't work around those other issues people have mentioned in the comments, but you'd struggle on those issues even more with a single regex.
var title = '';
var first_name = '';
var last_name = '';
var has_title = false;
if (name != null)
{
var new_name = name.split(" ");
// Check the first part for a title/prefix
if (/^(?:Dr|Mr|Mrs|Miss|Master)\.?$/i.test(new_name[0]))
{
title = new_name.shift();
has_title = true;
}
if (new_name.length > 1)
{
last_name = new_name.pop();
first_name = new_name.join(" ");
}
else if(has_title)
{
last_name = new_name.pop();
}
else
{
first_name = new_name.pop();
}
}
Adapted from Accepted Answer :)

Categories