Skip to content Skip to sidebar Skip to footer

Javascript Regexp - Replace Function Should Decide Not To Replace Matched String To Let Other Parenthesized Submatch Strings Work With A Match

This is fairly simple example, what I want is this: if replace function decides not to replace a 'match' - every other parenthesized submatch string: '('.+?':)' or '([^\s]+?:)' sho

Solution 1:

Give this a try. I did build a fast lookup from displayName to systemName to use:

var fieldNames = [
        { displayName: "Sender", systemName: "from_field"},
        { displayName: "Receiver(addressee)", systemName: "to_field"},
        { displayName: "Author", systemName: "author_id_field"}
    ],
    regex = /(?:#?"?)([^":]+)(?:"?):/i,
    map = {
        "Sender": "from_field",
        "Receiver(addressee)": "to_field",
        "Author": "author_id_field"
    };

var test = [
    '#"Sender":',
    '"Sender":',
    'Sender:',
    '#"Receiver(addressee)":',
    '"Receiver(addressee)":',
    'Receiver(addressee):',
    '#"Unknown":'
];

for (var i=0; i<test.length; i++) {
    var systemName = test[i].replace(regex, function(match, p1) {
       if (p1) return map[p1] || p1;
    });
    console.log("Display[%s] = System[%s]", test[i], systemName);
}
// output:// Display[#"Sender":] = System[from_field] // Display["Sender":] = System[from_field] // Display[Sender:] = System[from_field] // Display[#"Receiver(addressee)":] = System[to_field] // Display["Receiver(addressee)":] = System[to_field] // Display[Receiver(addressee):] = System[to_field]// Display[#"Unknown":] = System[Unknown] 

If the displayname being matched isn't known (_i.e. in the lookup map), it simply returns it as is.

Post a Comment for "Javascript Regexp - Replace Function Should Decide Not To Replace Matched String To Let Other Parenthesized Submatch Strings Work With A Match"