简体   繁体   中英

How to get the text between two special symbols(%) in a textarea?

How can i get the text between two % symbols in a textarea ??? I tried using jquery .keypress() event and got the result upto a certain level. But the keypress event will not get triggered if i delete or press backspace. If i go with .keyup() or .keydown(), how to detect the "%" character ... Here is what i tried out

var flag = false,
string = '';
$("#target").keypress(function(event) {
//  console.log(event,String.fromCharCode(event.keyCode));
if ( event.which == 37 ) {  
 if(flag === true){
  flag = false;      
  alert("REsult: "+ string.slice(1));
 }      
 flag= true;
}

//  console.log(flag, event.which);
if(flag === true){
 string = string + String.fromCharCode(event.which);
}
 console.log(string);   
});

Here is the bin

Am i going in the right path or is there any other better way... Please help me with your suggestions

try this,

var test_str = "text to get % Other text.... migh have % s ...";
var start_pos = test_str.indexOf('%') + 1;
var end_pos = test_str.indexOf('%',start_pos);
var text_to_get = test_str.substring(start_pos,end_pos)
alert(text_to_get);

How can i get the text between two % symbols in a textarea ???

var matches = /%([^%]*)%/.exec($("#target").val());
var result = matches ? matches[1] : null;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM