Tuesday, July 24, 2012

regex – Live replacement for regular expressions with Javascript



I\’m writing a code for live replacement of specific words in a text field as the user types.


I\’m using regex and javascript:

The first array has the regular expressions to be found, and the second array has the words that should replace any them.



source = new Array(/\\srsrs\\s/,/\\sñ\\s/,/\\snaum\\s/,/\\svc\\s/,/\\scd\\s/,/\\sOq\\s/,/\\soke\\s/,/\\so\\sq\\s/,
/\\soque\\s/,/\\soqe\\s/,/\\spq\\s/,/\\sq\\s/,/\\sp\\/\\s/g,/\\spra\\s/,/\\sp\\s/,/\\stbm\\s/,
/\\stb\\s/,/\\std\\s/,/\\sblz\\s/,/\\saki\\s/,/\\svlw\\s/,/\\smara\\s/,/\\sqlq\\s/,/\\sqq\\s/,
/\\srpz\\s/,/\\smsm\\s/,/\\smto\\s/,/\\smtu\\s/,/\\sqro\\s/,/\\sqdo\\s/,/\\sqd\\s/,/\\sqnd\\s/,
/\\sqto\\s/,/\\sqm\\s/,/\\sjah\\s/, /\\sc\\/\\s/,/\\scmg\\s/,/\\s\\+\\sou\\s\\-\\s/,/\\sflw\\s/,
/\\sxau\\s/,/\\sto\\s/,/\\sta\\s/);
after = new Array(\"risos\",\"não\",\"não\",\"você\",\"cadê\",\"o que\",\"o que\",\"o que\",\"o que\",\"o que\",\"porque\",
\"que\",\"para\",\"para\",\"para\",\"também\",\"também\",\"tudo\",\"beleza\",\"aqui\",\"valeu\",\"maravilhoso\",
\"qualquer\",\"qualquer\",\"rapaz\",\"mesmo\",\"muito\",\"muito\",\"quero\",\"quando\",\"quando\",\"quando\",
\"quanto\",\"quem\",\"Já\",\"com\",\"comego\",\"mais ou menos\",\"falow\",\"tchau\",\"estou\",\"está\");


This is the function that does the replacement:



function replacement(){
for(i=0; i<source.length; i++){
newtext = \" \"+document.getElementById(\"translation\").value+\" \";
console.log(newtext);
if(myregex = newtext.match(source[i])){
newafter = after[i];
rafael = myregex+\" \";
document.getElementById(\"translation\").value = document.getElementById(\"translation\").value.replace(rafael, newafter);
}
}
}


My problem is every time the function is called to replace an expression with only one letter, the replacement is being made on the first occurrence of that letter, even within a word. I thought looking for that letter with \\s before and after would solve it, but it didn\’t.






Rating: 3 out of 5 based on 4 ratings



The post regex – Live replacement for regular expressions with Javascript appeared first on Javascript ASK.






via Javascript ASK http://javascriptask.phpfogapp.com/regex-live-replacement-for-regular-expressions-with-javascript.html

No comments:

Post a Comment