Translating a Paragraph does not work using translate.js - javascript

I'm using translate.js.
Short text sentences work but I'm finding that long paragraphs do not nor do elements embedded within elements as you'll see below.
Here's ALL THE CODE:
STEP 1:
the HTML:
<div class="company mar-left10">
<h4 class="trn">Sustainable Global Solutions' Mission</h4>
<p class="trn">Sustainable Global Solutions mission is to market, build, implement, and operate sustainable business methods throughout the US and worldwide. The end result of our efforts is to provide proven, proprietary, and economically efficient solutions to our food, fuel, and population crises at hand. Additionally our waste-to-energy systems can utilize solid waste gasification for renewable energy generation.</p>
</div>
STEP 2:
The JAVASCRIPT:
$(function () {
var t = {
//TITLE
"Sustainable Global Solutions' Mission": {
en: "Sustainable Global Solutions' Mission",
sp: "Misión de Sustainable Global Solutions"
},
//**THIS SECTION WILL NOT TRANSLATE!**
"Sustainable Global Solutions mission is to market, build, implement, and operate sustainable business methods throughout the US and worldwide. The end result of our efforts is to provide proven, proprietary, and economically efficient solutions to our food, fuel, and population crises at hand.Additionally our waste-to-energy systems can utilize solid waste gasification for renewable energy generation.": {
en: "Sustainable Global Solutions mission is to market, build, implement, and operate sustainable business methods throughout the US and worldwide. The end result of our efforts is to provide proven, proprietary, and economically efficient solutions to our food, fuel, and population crises at hand.Additionally our waste-to-energy systems can utilize solid waste gasification for renewable energy generation.",
sp: "La misión de Sustainable Global Solutions es comercializar, construir, implementar y operar métodos comerciales sostenibles en todo Estados Unidos y en todo el mundo. El resultado final de nuestros esfuerzos es proporcionar soluciones probadas, exclusivas y económicas soluciones eficientes para nuestras crisis de alimentación, combustible y población a la mano.Además, nuestros sistemas de conversión de residuos en energía pueden utilizar la gasificación de residuos sólidos para la generación de energía renovable."
},
};
var _t = $('body').translate({lang: "en", t: t});
var str = _t.g("translate");
console.log(str);
$(".lang_selector").click(function (ev) {
var lang = $(this).attr("data-value");
_t.lang(lang);
console.log(lang);
ev.preventDefault();
});
}
);
Any help would be greatly appreciated.
Thank you everyone

Figured it out.
SIMPLE as MAKING SURE EACH PLACE the text appears it is IDENTICAL.
Sustainable Global Solutions mission is to market, build, implement, and operate sustainable business methods throughout the US and worldwide. The end result of our efforts is to provide proven, proprietary, and economically efficient solutions to our food, fuel, and population crises at hand.Additionally our waste-to-energy systems can utilize solid waste gasification for renewable energy generation.
I made sure that it was so and WALA!
La misión de Sustainable Global Solutions es comercializar, construir, implementar y operar métodos comerciales sostenibles en todo Estados Unidos y en todo el mundo. El resultado final de nuestros esfuerzos es proporcionar soluciones probadas, exclusivas y económicas soluciones eficientes para nuestras crisis de alimentación, combustible y población a la mano.Además, nuestros sistemas de conversión de residuos en energía pueden utilizar la gasificación de residuos sólidos para la generación de energía renovable.
Thank you to I Wrestled a BEAR ONCE for helping me SEE THE LIGHT!

Related

how to use regex with 2 element to replace?

I have a string of characters that i want to amend partially by adding a span tag highlighting the words by changing the color. I have a regex that matches 2 different pattern that i am targeting. I can only change the first pattern like i want to but not the other one.
Can someone help please?
let regex = /make your life easier|forget about the “I have to’s”/gi,
let aboutUsText3:
"We have more than 10 years’ experience in the sector and can offer you a professional and comprehensive real estate service. We’re here to [make your life easier], so that you can forget about the [“I have to’s”]. We can give you advice on whatever you need, whether it’s refurbishments, interior design, decoration, rental management, valuation of investments, or anything else. We’re here for you.",
const spannedText2 =
locale === "es"
? es.aboutUsText3
: aboutUsText3.replace(
regex.t3,
[
`<span class="fw-bold text-span">${strEnToSpan[2]}
</span>`,
`<span class="fw-bold text-span">${strEnToSpan[3]}</span>`,
].shift()
);
when i call the spannedText function only one element is highlighted.
what would be the best way to achieve this?
the output should be as follow:
<p>We have more than 10 years’ experience in the sector and can offer you a professional and comprehensive real estate service. We’re here to <span classname="bold">make your life easier</span>, so that you can forget about the <span classname="bold">“I have to’s”</span>. We can give you advice on whatever you need, whether it’s refurbishments, interior design, decoration, rental management, valuation of investments, or anything else. We’re here for you.",<P>
A Simple Alternative
In your example the sections to be highlighted are wrapped in brackets:
[text to be highlighted]
So you could just match the brackets and replace them with a span. This would be much easier to maintain and make work with multiple languages.
The regex matches the brackets and captures the text within:
/\[(.*?)\]/g
And we surround the captured text $1 with a span:
text.replace(/\[(.*?)\]/g, `<span class="bold">$1</span>`);
You might also want to look at using a JavaScript markdown library like Marked.js for more complex text transformations.
Run the snippet to understand how it works
function setLocale(locale) {
let text = locale === "es" ? aboutUsText.es : aboutUsText.en;
aboutUs.innerHTML = text.replace(/\[(.*?)\]/g, `<span class="bold">$1</span>`);
}
let aboutUsText = {
en: `We have more than 10 years’ experience in the sector and can offer you a professional and comprehensive real estate service. We’re here to [make your life easier], so that you can forget about the [“I have to’s”]. We can give you advice on whatever you need, whether it’s refurbishments, interior design, decoration, rental management, valuation of investments, or anything else. We’re here for you.`,
es: `Contamos con más de 10 años de experiencia en el sector y podemos ofrecerle un servicio inmobiliario profesional e integral. Estamos aquí para [hacer tu vida más fácil], para que te olvides de los [“tengo que”]. Podemos asesorarte en lo que necesites, ya sean reformas, interiorismo, decoración, gestión de alquileres, valoración de inversiones, o cualquier otro. Estamos aquí por tí.`
};
setLocale("en");
body {
font-family: sans-serif;
padding: 1em;
}
.bold {
font-weight: bold;
background-color: yellow;
}
<input type="radio" name="locale" value="en" onchange="setLocale(this.value)" checked> English
<input type="radio" name="locale" value="es" onchange="setLocale(this.value)"> Español
<p id="aboutUs"></p>

How to save whether a user clicked a button or not, and if so run a function

I have two functions translate_fr and translate_en, onClick when you click FR or EN the paragraphs are swapped either to english or french by grabbing their id's with inner.html
These two functions run on every html page, but obviously when refreshed or changing pages the onclick function reverts back to normal. So for instance if the user presses the FR button I want all the translate_fr functions on the other pages to run once the page loads, swapping the english paragraphs to french.
I need a way to store the users button click with local storage, and then a conditional statement saying if the user pressed EN run function translate_en else if FR then run function translate_fr.
Is this possible? I am VERY new to JavaScript and unfamiliar with local storage. I have no way how to do this. Here is the website on its domain lionkuts.ca for any other reference. I put two paragraphs as an example, though as you can see in the image I did this for every paragraph in the website.
function translate_en(){
document.getElementById("intro").innerHTML = `Here at Lion Kuts we are a cat only establishment that offers a full range of services from complete grooming, bathing to boarding. You and your pet will be thrilled to know that only professional, natural and biodegradeable products are used, any sensitivities or allergies will not be a problem.`;
}
function translate_fr(){
document.getElementById("intro").innerHTML = `Chez Coupe Lion, nous ne sommes qu'un chat établissement offrant une gamme complète de services du toilettage complet, de la baignade à l'embarquement.Vous et votre animal sera ravi de savoir que seul un professionnel, des produits naturels et biodégradables sont utilisés, tout les sensibilités ou les allergies ne seront pas un problème.`;
}
<div class="wrapper3">
<button class="translate" id="click1" type="button"onclick="translate_en()">EN
</button>
<button class="translate" id="click2"
type="button" onclick="translate_fr()">FR
</button>
</div>
<p id="intro">
Here at Lion Kuts we are a cat only
establishment that offers a full range of services
from complete grooming, bathing to boarding. You and
your pet will be thrilled to know that only professional,
natural and biodegradeable products are used, any
sensitivities or allergies will not be a problem.
</p>
You can use Window.localStorage to save the current language, and then use Window.onload to check the language.
Window.localStorage
Window.onload
function translate_en(){
Window.localStorage.setItem("language", "EN");
//translate the web page
} //translate_fr is same, but with french
Window.onload = (e) => {
let language = Window.localStorage.getItem("language");
if(language === "EN"){
translate_en();
} else if(language === "FR"){
translate_fr();
} else {
translate_en();//Default (if null)
}
}

Reset i18next on user action

I want to reset i18next translations on my web app. I am currently trying this:
// After user action:
i18n.init({
lng: language
});
$('body').i18n();
But its not working as i expected. Translations who are inyected using [prepend] or [append] are being duplicated.
<a class="landing-secondary-section-endlink" data-i18n="[prepend]landing-secondary-section-teach" href="http://..." target="_blank">Descubre una nueva forma de enseñar.Irakasteko era berri bat aurkitu.Scopri una nuova forma di insegnare.Descubre una nueva forma de enseñar.Discover a new way of teaching.Descubre una nueva forma de enseñar.Irakasteko era berri bat aurkitu.Descubre una nueva forma de enseñar.<span class="landing__link-underline"></span></a>
I solved this by removing all translations first.

Read JSon string with Javascript and PHP

In a Javascript file i receive this JSon string into a hidden html string:
<input id="page_json_language_index" type="hidden" value="[{"id":"label_accept_terms","fr":"En cliquant sur le bouton ci-dessous, vous accepter de respecter les "},{"id":"label_and","fr":" et la "},{"id":"label_birthdate","fr":"Anniversaire"},{"id":"label_bottom_about","fr":"\u00c0 propos de GayUrban"},{"id":"label_bottom_contact","fr":"Contactez-nous"},{"id":"label_bottom_copyright","fr":"\u00a9 2010-2013 GayUrban.Com - Tous droits r\u00e9serv\u00e9s"},{"id":"label_bottom_privacypolicy","fr":"Vie priv\u00e9e"},{"id":"label_bottom_termsofuse","fr":"Conditions d`...mon courriel"},{"id":"label_signon_twitter","fr":"Avec Twitter"},{"id":"label_slogan","fr":"LE site des rencontres LGBT !"},{"id":"label_terms_of_use","fr":"Conditions d`utilisation"},{"id":"label_title","fr":"Bienvenue sur GayUrban | LE site des rencontres LGBT !"},{"id":"label_transgender","fr":"Transgendre"},{"id":"label_username","fr":"Nom d`utilisateur"},{"id":"label_wait_create_profile","fr":"Un moment SVP, Cr\u00e9ation de votre profil en cours..."},{"id":"label_your_gender","fr":"Votre \u00eate"}]">
from MySQL database in user language (this example is in French (fr) so, i need to access in Javascript to each "id" and each value of this 'id"
Example : for the first "id"
i need to obtain on separate variables for each ID and VALUE
var label = "label_accept_terms";
and other variable
var value = "En cliquant sur le bouton ci-dessous, vous accepter de respecter les "
so i have a problem to read and affected each ID with good label and value.
Thank you for your helping !
I must point out that you've made a mistake in your HTML. You should escape the quotes to avoid breaking attributes, for example, simply replace them with apostrophe:
<input id="page_json_language_index" type="hidden" value='[{"id":"label_accept_terms","fr":"En cliquant sur le bouton ci-dessous, vous accepter de respecter les "},{"id":"label_and","fr":" et la "},{"id":"label_birthdate","fr":"Anniversaire"},{"id":"label_bottom_about","fr":"\u00c0 propos de GayUrban"},{"id":"label_bottom_contact","fr":"Contactez-nous"},{"id":"label_bottom_copyright","fr":"\u00a9 2010-2013 GayUrban.Com - Tous droits r\u00e9serv\u00e9s"},{"id":"label_bottom_privacypolicy","fr":"Vie priv\u00e9e"},{"id":"label_bottom_termsofuse","fr":"Conditions d`...mon courriel"},{"id":"label_signon_twitter","fr":"Avec Twitter"},{"id":"label_slogan","fr":"LE site des rencontres LGBT !"},{"id":"label_terms_of_use","fr":"Conditions d`utilisation"},{"id":"label_title","fr":"Bienvenue sur GayUrban | LE site des rencontres LGBT !"},{"id":"label_transgender","fr":"Transgendre"},{"id":"label_username","fr":"Nom d`utilisateur"},{"id":"label_wait_create_profile","fr":"Un moment SVP, Cr\u00e9ation de votre profil en cours..."},{"id":"label_your_gender","fr":"Votre \u00eate"}]'>
JSON.parse is the best way to convert JSON string, but it's not surpported by old IE (e.g. IE6). You can use JSON2 to make it compatible, or just simply use eval().
Aware that abuse of eval() may lead to XSS (Cross Site Scripting) vulnerability. Make sure that the JSON you're about to parse is safe (doesn't include malicious Javascript).
Here's an example to read all id:
<input id="page_json_language_index" type="hidden" value='[{"id":"label_accept_terms","fr":"En cliquant sur le bouton ci-dessous, vous accepter de respecter les "},{"id":"label_and","fr":" et la "},{"id":"label_birthdate","fr":"Anniversaire"},{"id":"label_bottom_about","fr":"\u00c0 propos de GayUrban"},{"id":"label_bottom_contact","fr":"Contactez-nous"},{"id":"label_bottom_copyright","fr":"\u00a9 2010-2013 GayUrban.Com - Tous droits r\u00e9serv\u00e9s"},{"id":"label_bottom_privacypolicy","fr":"Vie priv\u00e9e"},{"id":"label_bottom_termsofuse","fr":"Conditions d`...mon courriel"},{"id":"label_signon_twitter","fr":"Avec Twitter"},{"id":"label_slogan","fr":"LE site des rencontres LGBT !"},{"id":"label_terms_of_use","fr":"Conditions d`utilisation"},{"id":"label_title","fr":"Bienvenue sur GayUrban | LE site des rencontres LGBT !"},{"id":"label_transgender","fr":"Transgendre"},{"id":"label_username","fr":"Nom d`utilisateur"},{"id":"label_wait_create_profile","fr":"Un moment SVP, Cr\u00e9ation de votre profil en cours..."},{"id":"label_your_gender","fr":"Votre \u00eate"}]'>
<textarea id="debug-console" cols="50" rows="20"></textarea>
<script type="text/javascript">
var arr = eval(document.getElementById("page_json_language_index").value),
output = document.getElementById("debug-console");
//output all id
for(var i=0; i<arr.length; i++)
output.value += [i, ": ", arr[i].id, "\n"].join("");
//show the first id
alert(arr[0].id);
</script>
Actually you can directly output JSON to Javascript.
To meet your needs, I think here's what you need.
<?php
...
$data = ...; //for example, from mysql query results
$language = "fr"; //you can replace it with it/en/zh...
...
?>
<input id="some_id"></input>
<script>
(function() {
var i18n = "<?php echo json_encode($data); ?>",
lang = "<?php echo $language; ?>", //language
data = eval(i18n); //you can also use JSON.parse/jQuery.parseJSON ...
for(var i=0; i<data.length; i++) {
document.getElementById(data[i].id).value = data[i][lang]; //a general way to read object's attribute in Javascript
}
})()
</script>
i need to obtain on separate variables for each ID and VALUE
This is not the way to go, you don't want to pollute your scope with a bunch of variables. What you have is a collection (array of objects). You can loop such collection and access the properties you need.
var input = document.getElementById('page_json_language_index');
var data = JSON.parse(input.value); // collection
the goal is to assign to each pair of (id, fr) value into a jquery
label
var label = function(lab) {
return '<label id="'+ lab.id +'">'+ lab.fr +'</label>';
};
var labels = data.map(label);
You can also make it a jQuery collection:
var $labels = $(labels.join(''));
Then you can append it to any container:
$labels.appendTo('body');

extract words in string with unicode characters

In javascript (nodejs) I need to index text strings with unicode characters, i.e given a string like:
"Bonjour à tous le monde,
je voulais être le premier à vous dire:
-'comment ça va'
-<est-ce qu'il fait beau?>"
I want to get the following array of words :
["Bonjour", "à", "tous", "le", "monde", "je", "voulais", "être", ... "beau"]
How can I achieve that using regex or any other means ?
ps: I installed and tried the xregexp module which provides unicode support for javascript, but being utterly useless with regexes in general, I could not go very far ...
You can use the version of XRegExp bundled with addons which (amongst others) adds support for regex unicode categories. We are interested in the category not an unicode letter that is \P{L}.
You can then split your string by the regex XRegExp("\\P{L}+").
var s="Bonjour à tous le monde,\nje voulais être le premier à vous dire:\n -'comment ça va'\n -<est-ce qu'il fait beau?>";
var notALetter = XRegExp("\\P{L}+");
var words = XRegExp.split(s, notALetter);
See this fiddle.
You can probably use the library "uwords" - https://github.com/AlexAtNet/uwords. It extracts words from the text by grouping together characters from L* Unicode groups.
It works similar to XRegExp("\\p{L}+") but it is extremely fast.
Example:
var uwords = require('uwords');
var words = uwords('Bonjour à tous le monde,\n' +
'je voulais être le premier à vous dire:\n' +
'-\'comment ça va\'\n' +
'-<est-ce qu\'il fait beau?>');
console.log(words);
[ 'Bonjour',
'à',
'tous',
'le',
'monde',
'je',
'voulais',
'être',
'le',
'premier',
'à',
'vous',
'dire',
'comment',
'ça',
'va',
'est',
'ce',
'qu',
'il',
'fait',
'beau' ]
P.S. Sorry for being late - I hope it is still useful.
An idea could be to split the string by the various characters that are NOT part of words and then filter out empty strings:
var str = "Bonjour à tous le monde, je voulais être le premier à vous dire: -'comment ça va' -<est-ce qu'il fait beau?>";
var result = str.split(/[-:'"?\s><]+/).filter(function(item) { return item !== '' });
/*
["Bonjour", "à", "tous", "le", "monde,", "je", "voulais", "être", "le", "premier", "à", "vous", "ire", "comment", "ça", "va", "est", "ce", "qu", "il", "fait", "beau"]
*/
Similarly you could match by the negated character class above and you don't have to filter empty strings:
var result = str.match(/[^-:'"?\s><]+/g);

Categories