Reputation: 932
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 *'.
Upvotes: 6
Views: 353
Reputation: 18490
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);
Field Name* *abc
and want to strip out end as well, use (.*)\*.*
[\S\s]*
instead of .*
to skip over newlinesUpvotes: 1
Reputation: 92854
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 $
)Upvotes: 3
Reputation: 87203
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);
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);
Upvotes: 4