pinug pinug - 7 months ago 9
Javascript Question

regex to modify characters in specific case at the end of a word


im working on a translation project and i need to modify some characters at the end for example if user types words like:


typed word: "yilanin" => target word (what i want) :"yilaNG"

"suyunin" => "suyuNG"

"kalinin" => "kaliNG"

"batinin" => "batiNG"

etc etc...

But i have a problem: i don't want to modify "nin" characters if they are at the middle or at the beginning of a word like:

"kinindan*"" => **"kinindan"

"sininteki"" => "sininteki"

"nin" => "nin"

"ninkisi" => "ninkisi"

etc etc...

i mean every "xxxnin" to "xxxNG",

"xxxninxxx" to "xxxninxxx"(no modification),

"nin" to "nin" (no modification)...

i tried to explain my problem very clearly and bascially i hope you understand...



$(document).ready(function(){

$("#ta_1").keyup(function(event) {

var text2 = $(this).val();

text2 = text2.replace(/([abcçdefgğhıijklmnoöprsştuüvyzABCÇDEFGHIİJKLMNOÖPRSTUÜVYZ])nin$/g, '$1NG');

$("#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>




Answer

Try this

(\w)(nin)\b

Regex demo

$(document).ready(function(){
//setup before functions
var typingTimer;                //timer identifier
var doneTypingInterval = 1000;  //time in ms, 1 second for example
var $input = $('#myInput');

//user is "finished typing," do something
function doneTyping () {
  //do something
}
$("#ta_1").keyup(function(event) {

  var text2 = $(this).val();
  var re = /(\w)(nin)([^a-zA-Z])/g; 
var subst = '$1NG$3'; 
  text2 = text2.replace(re, subst);
var re = /(\w)(NG)(\w)/; 
var subst = '$1nin$3'; 
 text2 = text2.replace(re, subst);
  $("#ta_1").val(text2);
  clearTimeout(typingTimer);
  typingTimer = setTimeout(doneTyping, doneTypingInterval);
});
$("#ta_1").keydown(function(event) {
    clearTimeout(typingTimer);
}); 
function doneTyping () {
  var text2 = $("#ta_1").val();
  var re = /(\w)(nin)\b/g; 
var subst = '$1NG'; 
  text2 = text2.replace(re, subst);
  $("#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>

Comments