正则表达式获取两个字符之间的文本?

时间:2017-01-31 11:01:30

标签: javascript jquery regex string replace

我想在正斜杠之后和结束分组之前替换文本。

My text: 
<h3>notThisText/IWantToReplaceThis)<h3>

$('h3').text($('h3').text().replace(regEx, 'textReplaced'));

Wanted result after replace:
notThisText/textReplaced) 

我试过了

regex = /([^\/]+$)+/ //replaces the parantheses as well 
regex = \/([^\)]+) //replaces the slash as well 

但正如你在我的评论中所看到的,这些都不包括斜杠和结束的范例。有人可以帮忙吗?

5 个答案:

答案 0 :(得分:1)

/(?<=\/)[^)]+(?=\))/这样的模式在JS中不起作用,因为它的正则表达式引擎不支持lookbehind构造。因此,您应该使用以下解决方案之一:

s.replace(/(\/)[^)]+(\))/, '$1textReplaced$2')
s.replace(/(\/)[^)]+(?=\))/, '$1textReplaced')
s.replace(/(\/)[^)]+/, '$1textReplaced')
s.replace(/\/[^)]+\)/, '/textReplaced)')

(...)形成一个捕获组,可以使用替换模式中的$ +数字(反向引用)引用该捕获组。第一个解决方案是使用/),并将它们放入捕获组。如果您需要匹配连续的重叠匹配,请使用第二个解决方案(s.replace(/(\/)[^)]+(?=\))/, '$1textReplaced'))。如果最后不需要),则第三个解决方案(replace(/(\/)[^)]+/, '$1textReplaced'))将会执行。如果s.replace(/\/[^)]+\)/, '/textReplaced)')/是预先知道的静态值,则最后一个解决方案())将有效。

答案 1 :(得分:0)

var text = "notThisText/IWantToReplaceThis";
text = text.replace(/\/.*/, "/whatever");
output : "notThisText/whatever"`

答案 2 :(得分:0)

您可以使用str.split('/')

var text = 'notThisText/IWantToReplaceThis';
var splited = text.split('/');
splited[1] = 'yourDesireText';
var output = splited.join('/');
console.log(output);

答案 3 :(得分:0)

尝试以下:在你的情况下,startChar ='/',endChar =')',origString = $('h3')。text()

function customReplace(startChar, endChar, origString, replaceWith){
var strArray = origString.split(startChar);
return strArray[0] + startChar + replaceWith + endChar;
}

答案 4 :(得分:0)

首先,您没有明确定义要替换的文本格式和非替换部分的格式。例如,

  • notThisText是否包含任何斜杠/
  • IWantToReplaceThis是否包含任何括号)

由于存在太多不确定性,此处的答案仅显示模式与您的示例完全匹配:

yourText.replace(/(\/).*?(\))/g, '$1textReplaced$2')
相关问题