Create a regex to replace the last occurrence of a character in a string

Instead of RegEx, use String#substring and String.lastIndexOf as below

const str = 'Field Name* * ';
const replaceStr = 'mandatory';
const lastIndex = str.lastIndexOf('*');
const result = str.substring(0, lastIndex) + replaceStr + str.substring(lastIndex + 1);

console.log('Substitution result: ', result);

Still want to use RegEx?

const regex = /\*([^*]*)$/;
const str = 'Field Name* * Hello World!';
const replaceStr = ' mandatory';
const result = str.replace(regex, (m, $1) => replaceStr + $1);
console.log('Substitution result: ', result);


Short regex magic (shown on extended input str):

const regex = /\*(?=[^*]*$)/m,
      str = 'Field Name* * * * ',
      replaceStr = ' mandatory',
      result = str.replace(regex, replaceStr);
console.log('Substitution result: ', result);

  • (?=[^*]*$) - lookahead positive assertion, ensures that the former \* is matched only if it's followed by [^*]* (non-asterisk char right up to the end of the string $)

Just let .* consume before last * and capture it. Replace with captured $1 mandatory.

let str = 'Field Name* * ';
let res = str.replace(/(.*)\*/,'$1mandatory');
console.log(res);

See this demo at regex101

  • If you have Field Name* *abc and want to strip out end as well, use (.*)\*.*
  • If you have multline input, use [\S\s]* instead of .* to skip over newlines