Regex取代“;t〃;用“;T”;只有在“;a”"o”"u〃;使用javascript

Regex to replace "t" with "T" only if succeeded by "a","o","u" with javascript

本文关键字:quot javascript 使用 取代 Regex      更新时间:2023-09-26

在Javascript中,我想用"t"代替"t",但前提是"t"后面的字符后面有"a"、"o"、"u"。例如:字符串:tatotu,目标字符串:tatotu我找不到Regex。

$(document).ready(function(){
$("#ta_1").keyup(function(event) {
  
  var text = $(this).val();
  text = text.replace("t, (''a|''o|''u)","T");
  $("#ta_1").val(text);
});
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
 
<body>
  
   <textarea id="ta_1" rows="5" cols="28" ></textarea>
    
</body>
  
</html>

使用带有lookahead的实际正则表达式。

$(document).ready(function() {
  $("#ta_1").keyup(function(event) {
    var text = $(this).val();
    text = text.replace(/t(?=a|o|u)/g, "T");
    $("#ta_1").val(text);
  });
});
<!DOCTYPE html>
<html lang="en">
<head>
  <title></title>
  <meta charset="utf-8" />
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
  <textarea id="ta_1" rows="5" cols="28"></textarea>
</body>
</html>

使用replace回调的简单解决方案:

...
text = text.replace(/(t)(a|o|u)/gi, function(m, p1, p2) { 
    return p1.toUpperCase() + p2; 
});

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter

这样一个简单的正则表达式就足够了。

Regex:t(a|o|u)

替换为:T$1T'1

Regex101演示

试试这个

var map={"ta":"Ta", "to": "To", "tu": "Tu"}; 
    var regex = new RegExp(Object.keys(map).join("|"), "g"); 
    var output = "tatotu".replace(regex, function(matched){return map[matched]});
alert(output);

var str = "tatatou";
var result = str.replace(/t([aou])/g, "T$1");