locale-url-solver is a nodejs module.
It helps you to to get the locale related to your urls. But first you have to specify your own policy.
It can be used :
You have to be familiar with regular expressions
$ npm install locale-url-solver
const LocaleUrlSolver = require('locale-url-solver');
Init with a litteral object :
LocaleUrlSolver({
default: 'en',
locales: {
'fr': /^http(s)?:\/\/fr\.[^\/]+($|\/)(.*)$/,
'de|es': /^http(s)?:\/\/([^\/]*\/LANG($|\/)|LANG\.[^\/]+($|\/)(.*)$)/
}
});
A key is a locale
LocaleUrlSolver({
default: 'en',
locales: {
'de': /^http(s)?:\/\/[^\/]*((.de)|\/de)($|\/)/,
'fr': /^http(s)?:\/\/fr\.[^\/]+($|\/)(.*)$/
}
});
LocaleUrlSolver.solve('http://www.website.com');
>> en
LocaleUrlSolver.solve('http://fr.website.com');
>> fr
LocaleUrlSolver.solve('http://fr.website.com/path/is/long');
>> fr
LocaleUrlSolver.solve('http://www.website.de');
>> de
LocaleUrlSolver.solve('http://www.website.com/de');
>> de
A key is a group of locales
You may have a global url policy, you can simplify with one pattern
LocaleUrlSolver({
default: 'en',
locales: {
'de|fr|es': /^http(s)?:\/\/([^\/]*\/LANG($|\/)|LANG\.[^\/]+($|\/)(.*)$)/
}
});
LocaleUrlSolver.solve('http://www.website.com/es/path/is/long/');
>> es
It looks for the 'LANG' word, you can change this keyword
LocaleUrlSolver({
default: 'en',
locales: {
'de|fr|es': /^http(s)?:\/\/([^\/]*\/STUFF($|\/)|STUFF\.[^\/]+($|\/)(.*)$)/
},
search:'STUFF'
});
LocaleUrlSolver({
default: 'en',
locales: {
'fr': /^http(s)?:\/\/fr\.[^\/]+($|\/)(.*)$/,
'de|es': /^http(s)?:\/\/([^\/]*\/LANG($|\/)|LANG\.[^\/]+($|\/)(.*)$)/
}
});
Default locale can be explicitly set
LocaleUrlSolver({
default: 'en',
locales: {
'fr': /^http(s)?:\/\/fr\.[^\/]+($|\/)(.*)$/,
'de|es': /^http(s)?:\/\/([^\/]*\/LANG($|\/)|LANG\.[^\/]+($|\/)(.*)$)/
}
});
LocaleUrlSolver.getDefault();
>> en
If not specified, the default locale is the first key
LocaleUrlSolver({
locales: {
'fr': /^http(s)?:\/\/fr\.[^\/]+($|\/)(.*)$/,
'de|es': /^http(s)?:\/\/([^\/]*\/LANG($|\/)|LANG\.[^\/]+($|\/)(.*)$)/
}
});
LocaleUrlSolver.getDefault();
>> fr
LocaleUrlSolver.getLocales();
>> [ 'de', 'en', 'fr', 'it' ]
LocaleUrlSolver.isSet('it');
>> true
The first match returns the locale. So the order of the rules is important:
This module is 100% covered by 33 tests