user42760
user42760

Reputation: 85

Replace commas with Javascript

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.

Upvotes: 0

Views: 125

Answers (3)

iAmOren
iAmOren

Reputation: 2804

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;
}

Upvotes: 0

ˈvɔlə
ˈvɔlə

Reputation: 10242

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;
    }
}

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074385

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"));
}

Upvotes: 1

Related Questions