Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 *'.

like image 833
Sunny Avatar asked Nov 22 '19 05:11

Sunny


People also ask

How do you replace the last occurrence of a character in a string?

To replace the last occurrence of a character in a string: Use the lastIndexOf() method to get the last index of the character. Call the substring() method twice, to get the parts of the string before and after the character to be replaced. Add the replacement character between the two calls to the substring method.

How do you replace a character in regex?

To use RegEx, the first argument of replace will be replaced with regex syntax, for example /regex/ . This syntax serves as a pattern where any parts of the string that match it will be replaced with the new substring. The string 3foobar4 matches the regex /\d. *\d/ , so it is replaced.

What does \f mean in regex?

Definition and Usage The \f metacharacter matches form feed characters.

Can I use regex in replace?

The Regex. Replace(String, String, MatchEvaluator, RegexOptions) method is useful for replacing a regular expression match if any of the following conditions is true: If the replacement string cannot readily be specified by a regular expression replacement pattern.


2 Answers

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);
like image 85
Tushar Avatar answered Oct 17 '22 18:10

Tushar


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 $)
like image 45
RomanPerekhrest Avatar answered Oct 17 '22 18:10

RomanPerekhrest