Alexander Derck
Alexander Derck

Reputation: 14498

Using regex to find descriptions in the javascript files of MVC project?

I have an ASP.NET MVC application where I pass certain translations to my views so I can show my pages in different languages (the translations are used in the corresponding javascript file, not in the razor view). Now I have a List<string> for every view which contains the descriptions of the translations I need, which is a real pain to maintain of course. If I change a single javascript file, I need to update the corresponding collection etc.

Now I had a crazy idea, in all my js files I use dictionary.find('<description>') to get access to the translations. Would it be a bad idea to populate my lists when the model is first accessed by using a regex on the javascript files? It would look something like this:

protected static List<string> Descriptions;

private static Model()
{
    string basePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Scripts");
    string fileName = Path.Combine(basePath, $"{modelName}.js");
    string javascript = File.ReadAllText(fileName);
    Regex regex = new Regex(@"dictionary\.find\('(.+?)'\)");
    var matches = regex.Matches(javascript)
                       .Cast<Match>()
                       .Select(m => m.Groups[1].Value)
                       .ToList();
}

This code basically reads the javascript file that is used for the view and finds all the words that are used between dictionary.find('...'). I've already tested this, and it seems to work but my question is:

How bad of an idea is this? Or is it good? My models/scripts are named very consistently etc so that wouldn't be a problem.

Upvotes: 0

Views: 98

Answers (1)

colin-higgins
colin-higgins

Reputation: 1117

I would think that you would want to store data in file types meant for that.

I think there is no problem having a conventions based approach to this, but you might be better suited putting your <description> data in a JSON file. The JSON file could live right next to your js files.

If you do that, you can just load up your translations by using a json serializer and you won't have to muck around with regex.

EDIT: I think it would still be a good idea to have a test verifying that all of your expected files do exist and match your expected format.

Upvotes: 1

Related Questions