简体   繁体   English

在javascript中使用正则表达式替换字符的奇数出现

[英]replace odd occurrences of a character using regex in javascript

I have a string which contains '#'. 我有一个包含“#”的字符串。 I want to replace occurrence of only odd '#' with something else. 我想用其他东西代替仅出现的奇数“#”。

For eg for below string 对于例如下面的字符串

This is my string # This is my string # This is my string # This is my string #

output should be 输出应该是

This is my string # This is my string '' This is my string # This is my string ''

Note : considering occurrence starts with 0 注意:考虑发生从0开始

([^#]*#[^#]*)#

You can use this.Replace by $1" .See demo. 您可以使用this.Replace by $1" 。请参见演示。

https://regex101.com/r/cT0hV4/9 https://regex101.com/r/cT0hV4/9

var re = /([^#]*#[^#]*)#/gm; 
var str = 'This is my string # This is my string # This is my string # This is my string #';
var subst = '$1"'; 

var result = str.replace(re, subst);

Try using this regex: 尝试使用此正则表达式:

#(.*?(?:#|$))

Regex Demo 正则表达式演示

EDIT: 编辑:

var reg = /#(.*?(?:#|$))/; 
var message = 'This is my string # This is my string # This is my string # This is my string #';
var substitue = '$1"'; 

var result = message.replace(reg, substitue);
alert(result);

JSFIDDLE DEMO JSFIDDLE演示

您可以使用以下正则表达式来执行此操作

str.replace(/(#.*?)#/g, '$1"')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM