Skip to content Skip to sidebar Skip to footer

What Is A Simple Solution To Editable-by-end-user Text Replacement Placeholders?

Here's the problem I'm trying to solve: a user can display a custom 4-character title for something on a web site, e.g. NEWS. I want to add support for a way that a user can speci

Solution 1:

Javascript solution:

var str = 'abcd [foo][bar][baz] [[x] <[[x]> <[x]>';

str = str.replace( /(\[)?\[(\w+)\]/g, function ( match, escaped, icon ) {
    return escaped ? '[' + icon + ']' : '$' + icon;
});

// "abcd $foo$bar$baz [x] <[x]> <$x>"

Solution 2:

Just for demonstration, here is a more elegant JS solution which uses replace:

var output = str.replace(/\[(\w+)\]/g, function(match, icon, offset) {
    if (offset>0 && str.charAt(offset-1) == '[') // if previous existed and was [return match.slice(1); // return the match but without opening [// elsereturn'<i class="icon-' + icon + '" />'; // or whatever you want to do
});

Solution 3:

Solution for Ruby

You can use look-behind to prevent the substring [word] in [[word] from matching:

(?<!\[)\[(\w+)\]

The look-behind (?<!\[) simply checks [ does not appear before the string we want to match.

DEMO

Solution for JS

For JS workaround, since it doesn't have look-behind:

// Match one non-opening-bracket character, then the [word],// but the closing bracket is not consumed, for the case// of consecutive [word1][word2]var regex = /(^|[^\[])\[(\w+)(?=\])/g;
var arr;

var output = "";
var lastAppend = 0;

while ((arr = regex.exec(inputString)) !== null) {
    // Append substring from index of lastAppend to right before opening [// lastAppend will either be at beginning of the string (0)// OR right after closing ] from previous match
    output += inputString.substring(lastAppend, arr.index + arr[1].length);
    output += "$" + arr[2];

    // Need to offset by 1 to skip the closing ] (not consumed)
    lastAppend = regex.lastIndex + 1;
}

output += inputString.substring(lastAppend);

It is quite ugly. I am not sure if there is a more elegant way.

Post a Comment for "What Is A Simple Solution To Editable-by-end-user Text Replacement Placeholders?"