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

时间:2015-09-03 08:35:40

标签: javascript regex

我有一个包含'#'的字符串。我想替换只有奇怪的#'#'用其他东西。

例如对于下面的字符串

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

输出应该是

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

注意:考虑事件从0开始

3 个答案:

答案 0 :(得分:2)

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

您可以$1"使用此。替换。请参阅演示。

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

答案 1 :(得分:1)

尝试使用此正则表达式:

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

<强> Regex Demo

修改

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

答案 2 :(得分:1)

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

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