6

I need to create a regex which should look for the last '*' irrespective of the whitespace in the string. Then, I need to replace that string with some text.

Currently, it is replacing the first occurence of '*' in the string.

How do I fix it?

Here's my code:

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

Here, the output should be 'Field Name* mandatory'. But what I get is 'Field Name mandatory *'.

Sunny
  • 902
  • 3
  • 18
  • 41

3 Answers3

4

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);
Tushar
  • 85,780
  • 21
  • 159
  • 179
3

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 $)
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
1

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
bobble bubble
  • 16,888
  • 3
  • 27
  • 46