Reputation: 63
To clarify, I'm absolutely terrible with Regular Expressions. I've found a few examples of this on here already but I simply have no idea how to implement it for my usage.
I'm doing (rather poorly) a translation from English to French in JavaScript for a client, but I'm running into a problem where it's translating variable names and select-option values, which obviously breaks search functions and entry functions.
My existing code:
var englishStrings = new Array();
englishStrings[0] = /List Members/g;
var frenchStrings = new Array();
frenchStrings[0] = "Listes des membres";
$(document).ready(function() {
//alert(language);
if (language == "English" || language == null)
{
$("#language_link").text("Voir en français");
var strNewString = $('body').html();
strNewString = strNewString.replace(/Nccp/g, 'NCCP');
strNewString = strNewString.replace(/Actions/g, 'Menu');
strNewString = strNewString.replace(/Id/g, 'ID');
}
else
{
$("#language_link").text("View in English");
var strNewString = $('body').html();
strNewString = strNewString.replace(/Nccp/g, 'NCCP');
strNewString = strNewString.replace(/Actions/g, 'Menu');
strNewString = strNewString.replace(/Id/g, 'ID');
$.each(englishStrings, function(index, value) {
strNewString = strNewString.replace(value, frenchStrings[index]);
});
strNewString = strNewString.replace('Voir', 'View');
}
$('body').html(strNewString);
});
I would like to change the regex find strings (/List Members/g) to exclude quotes within the search itself, not as an afterthought as I've seen examples of.
Ex:
<option value="List Members">List Members</option>
currently becomes
<option value="Listes des membres">Listes des membres</option>
I want it to become
<option value="List Members">Listes des membres</option>
Excluding the string surrounded by quotation marks.
Again, I know regex is a poor choice for manipulating HTML, I regret doing it this way but we've already invested quite a bit of time doing it like this.
Upvotes: 2
Views: 554
Reputation: 4499
If I understand you correctly, you may try to use something like this:
replace(/([^"'])List Members([^"'])/g, '$1Listes des membres$2')
(or, somewhat more precise variant: replace(/([^"'])List Members\1/g, '$1Listes des membres$1')
- will only exclude strings with matching opening and closing quotes)
In many dialects it would be possible to do without adding backreferences to the substituting string, like so:
replace(/(?<!'|")List Members(?!'|")/, 'Listes des membres') # won't work in JS!
Here we have negative lookbehind check at the beginning and negative lookahead at the end. Unfortunately, JavaScript regex engine doesn't support lookbehind syntax, so it's only possible to implement a lookahead part of the expression:
replace(/List Members(?!'|")/, 'Listes des membres')`
This one will exclude all strings ending with apostrophe or quotation mark (it will not check for an opening quote at all).
And yes, regex is indeed a poor choice for manipulating HTML :)
Upvotes: 1