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 *'.
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.
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.
Definition and Usage The \f metacharacter matches form feed characters.
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.
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 $
)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With