pinug
pinug

Reputation: 211

print out last character after regex

I want to print following character after matched character(ad) but i don't know how to call it as an argument, any help ?

$(document).ready(function(){

$("#ta_1").keyup(function(event) {
  
  var text2 = $(this).val();
  
  text2 = text2.replace(/ad(?=a|ı|o|u|R|T|S|B|q|Y|L|Ğ|I|D)/g, "D$2");
  
  $("#ta_1").val(text2);
  
});
});
<!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>

Upvotes: 0

Views: 47

Answers (1)

Adam Katz
Adam Katz

Reputation: 16138

There are a few ways to do this, and your code was pretty close to one of them; you just had to remove the $1. Another solution would be to capture rather than lookahead.

"adoadR".replace(/ad(?=a|ı|o|u|R|T|S|B|q|Y|L|Ğ|I|D)/g, "D$1"); // #0: "D$1oD$1R"
"adoadR".replace(/ad(?=a|ı|o|u|R|T|S|B|q|Y|L|Ğ|I|D)/g, "D");   // #1: "DoDR"
"adoadR".replace(/ad(a|ı|o|u|R|T|S|B|q|Y|L|Ğ|I|D)/g, "D$1");   // #2: "DoDR"

To further optimize, you should also collapse that alternation into a character class:

"adoadR".replace(/ad(?=[aıouRTSBqYLĞID])/g, "D"); // #3: "DoDR"
"adoadR".replace(/ad([aıouRTSBqYLĞID])/g, "D$1"); // #4: "DoDR"

Since capturing is expensive, I'd recommend against it since you don't need it.

My #3 is the best solution.

Upvotes: 1

Related Questions