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.

7
  • valid regular expression would be /,/g Commented Jul 28, 2020 at 13:29
  • My typo. Sorry. Commented Jul 28, 2020 at 13:30
  • What are your expectations? Commented Jul 28, 2020 at 13:30
  • Expectations? just want to know how to replace the second comma, if there is one, with "by". Commented Jul 28, 2020 at 13:31
  • Possible duplicate of Match at every second occurrence. Use that in combination with replace. Commented Jul 28, 2020 at 13:31

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Very nice solution, Thanks!
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;
    }
}

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.