I want to add one character for every special character in a string by regular expression i tried below expression but it is adding after the special character.
I expect the output to add one character for every special character in a string.
var string1="aaa!dd,"
var expressionResult = text.replace(/([\/,!?_])/g, '/');
the output should be aaa/!dd/,
I want to add one character for every special character in a string by regular expression i tried below expression but it is adding after the special character.
I expect the output to add one character for every special character in a string.
var string1="aaa!dd,"
var expressionResult = text.replace(/([\/,!?_])/g, '/');
the output should be aaa/!dd/,
Share Improve this question asked May 31, 2019 at 9:50 saisai 671 silver badge10 bronze badges 1-
1
Use
text.replace(/[\/,!?_]/g, '/$&')
. BTW, your regex does not match every special character. What chars are "special" to you? – Wiktor Stribiżew Commented May 31, 2019 at 9:51
2 Answers
Reset to default 4You can use $1
in the replacement string to include the capture group's content in the replacement:
var string1="aaa!dd,"
var expressionResult = string1.replace(/([\/,!?_])/g, '/$1');
console.log(expressionResult);
More on MDN.
You don't need a capture group, though, you can use $&
to refer to the text matched by the main expression:
var string1="aaa!dd,"
var expressionResult = string1.replace(/[\/,!?_]/g, '/$&');
console.log(expressionResult);
(If you needed to do something more plex in the replacement, you can pass in a function as the second argument. It gets called with the overall match as its first argument, followed by arguments for each capture group; its return value is used in the resulting string. You don't need that here, but...)
You can use back reference to the group $&
MDN ref
var string1="aaa!dd,"
var expressionResult = string1.replace(/[\/,!?_]/g, '/$&');
console.log(expressionResult)
By special character if you mean everything else than alphabet and digits than you can change your regex to
[^a-z\d] - Match anything except alphabet and digit
var string1="aaa!dd,"
var expressionResult = string1.replace(/[^a-z\d]/g, '/$&');
console.log(expressionResult)