我有一个包含'#'的字符串。我想替换只有奇怪的#'#'用其他东西。
例如对于下面的字符串
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开始
答案 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"')