最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - Add one character before every special character in a string in javascript - Stack Overflow

programmeradmin3浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 4

You 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)

发布评论

评论列表(0)

  1. 暂无评论