用Javascript替换分隔字符串
我有一个字符串:用Javascript替换分隔字符串,javascript,regex,Javascript,Regex,我有一个字符串: Mr Blue has a //start blue house and a blue //end car. 我想用//start和//end替换带分隔符的字符串,因此字符串变成: Mr Blue has a car. 我试过了 var res = str.replace(\//start(.*?)\//end, ""); 它不起作用。您可以使用此正则表达式: \/\/start(.*?)\/\/end Javascript代码 var re = /\/\/start
Mr Blue has a //start blue house and a blue //end car.
我想用//start和//end替换带分隔符的字符串,因此字符串变成:
Mr Blue has a car.
我试过了
var res = str.replace(\//start(.*?)\//end, "");
它不起作用。您可以使用此正则表达式:
\/\/start(.*?)\/\/end
Javascript代码
var re = /\/\/start(.*?)\/\/end/;
var str = ' //start blue house and a blue //end';
var result = str.replace(re, '$1');
您可以使用以下选项:
var string = "Mr Blue has a //start blue house and a blue //end car. "
string = string.replace(/\/\/.*?\/\/\w+\s+/g, "");
alert(string)
输出:
演示:
正则表达式解释:
您可以使用这个正则表达式来匹配分隔符之间的任何字符,包括换行符\/\/start。|\n*\/\/end我认为这在Javascript中都是无效的。试试/\/\/start.*?\/\/end/@LABLEBI:周围的空格呢?你需要只保留1个吗?是否会有//开始或//结束词?问题是/\/\/start.*.\/\/end/中的点匹配除新行以外的任何字符,我想匹配分隔符之间的任何内容,包括新行great,但是当我在字符串中执行换行操作时,reg不起任何作用more@LABLEBI您可以这样使用单行标志:?s\/\/start.*?\/\/end,也可以使用\/\/start[\s\s]*?\/\/end
Mr Blue has a car.
//.*?//\w+\s+
Match the character string “//” literally «//»
Match any single character that is NOT a line break character «.*?»
Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the character string “//” literally «//»
Match a single character that is a “word character” «\w+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match a single character that is a “whitespace character” «\s+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»