Rectangle 27 0

SimpleBasic Jquery or Javascript String Replace for Multiple Values?


$(function() {
    var REPLACEMENTS = {
        'example-phrase': 'Example Phrase',
        'example2-phrase': 'Example 2 Phrase',
        'example-solution': 'Example & Solution'
    }

    function doReplacement(input) {
        for (var key in REPLACEMENTS) {
            input = input.replace(key, REPLACEMENTS[key]);
        }

        return input;
    }

    $('h2').each(function() {
        var $this = $(this);
        $this.html(doReplacement($this.html()));
    });
});
h2
var REPLACEMENTS = {
    'example-phrase': 'Example Phrase',
    'example2-phrase': 'Example 2 Phrase',
    'example-solution': 'Example & Solution'
}

function doReplacement(input) {
    for (var key in REPLACEMENTS) {
        input = input.replace(key, REPLACEMENTS[key]);
    }

    return input;
}

Ah, luckily just running on 1 page and probably only 10-20 replacements will happen. Do I need some other code to have this run automatically as soon as the page loads?

Exactly how you have it is how I would need it. The string getting replaced are always the same and what needs to replace them is always the same. What about this code is a performance hindrance?

It depends on how often you will run this and how many replacements there will be. If you this with, say, 20 headlines and 50 possible replacements you don't really need to care about its performance. It might become an issue if you run this over thousands of texts with hundreds of replacements.

Might not be the most performant solution though. You might need to ask yourself: Do you need case insensitivity? Can a single input contain more than one of the strings that need to be replaced? Is the string itself exactly equal to the replacement key or does it contain it?

Perfect! Thank you. Answered accepted, exactly what I needed. I did have to change $ to jQuery for no conflict (I couldn't determine what other script was causing it) and changed h2 to .replacement so I could apply this function with a css class. jsfiddle.net/codeview/GSZLR

Note
Rectangle 27 0

SimpleBasic Jquery or Javascript String Replace for Multiple Values?


var ex1 = "example-phrase";
var res1 = ex1.replace("-", " ");
res1 = res1.toLowerCase().replace(/\b[a-z]/g, function(letter) {
    return letter.toUpperCase();
});
var ex3 = "example-solution";
var res3 = ex3.replace("-", " ");
res3 = res3.toLowerCase().replace(/\b[a-z]/g, function(letter) {
    return letter.toUpperCase();
});
res3 = res3.replace(" ", " & ");

I feel that checking every time you get a response isn't feasible.

The above solution works for the first case. For the 3rd case, just add the following,

Note