0

I have strings (painting title, painter name) that have one or two commas, such as Big House, Jone Doe or Big House, Blue, John Doe. These are captions for the actual paintings. And I want to replace the correct comma with by.

I can get the captions with

const captions = document.querySelectorAll('#gallery .caption');
    for (const caption of captions) {
        var new_caption = caption.textContent.toString();

If I use replace(","," by"), that gets me the first comma. Then replace(",/g", " by") does it for both. How do I replace just the second comma if there is one? Can't figure this out. Thanks.

ˈvɔlə
  • 9,204
  • 10
  • 63
  • 89
user42760
  • 85
  • 1
  • 7

3 Answers3

1

To replace only the last comma, you could use /,(?=[^,]*$)/, which looks for a comma and uses a lookahead assertion to ensure that it's only followed by text without a comma through the end of the string:

const rex = /,(?=[^,]*$)/;
test("Big House, Jone Doe");
test("Big House, Blue, John Doe");
test("Big House, Blue, with Tree, John Doe");

function test(str) {
    console.log(str, "=>", str.replace(rex, " by"));
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

For people who want to avoid regular expressions, you can define a replaceAt function:

String.prototype.replaceAt = function(index, replacement) {
    return this.substr(0, index) + replacement + this.substr(index + replacement.length);
}

Then, you can use lastIndexOf() to find out the last appearance of comma:

const captions = document.querySelectorAll('#gallery .caption');
    for (const caption of captions) {
        let indexOfLastComma = caption.textContent.lastIndexOf(',');
        let newCaption = caption.textContent.replaceAt(indexOfLastComma, ' by');
        caption.textContent = newCaption;
    }
}
ˈvɔlə
  • 9,204
  • 10
  • 63
  • 89
0

Try this:

var string="We don't need no education, The Wall, Pink Floyd";
var lastComma=string.lastIndexOf(",");
if(lastComma!=-1)
  string=string.slice(0,lastComma)+" by"+string.slice(lastComma+1);

Or, in a function:

function replaceLastCommaWithBy(string) {
  var lastComma=string.lastIndexOf(",");
  if(lastComma!=-1)
    string=string.slice(0,lastComma)+" by"+string.slice(lastComma+1);
  return string;
}
iAmOren
  • 2,760
  • 2
  • 11
  • 23