PDA

View Full Version : Using QString in evaluateJavaScript as agrument



kokilakr
17th June 2010, 09:09
Hello,

I need to send a string which contains newline to javascript function as an argument.


Example:
QString sampleString = "first line \n second line.";

const char *kModifyString="\
function modifyString(str)\
{\
return str;\
}\
modifyString(\"%1\");";

webFrame->evaluateJavaScript(QString(kModifyString).arg(samp leString ));

But %1 do not take QString with newline.

How can I handle this situation? I need to send sampleString to javascript function as argument.

Thanks,

borisbn
17th June 2010, 11:55
I had modified your code a little like this:


QString sampleString = "first \n second";

const char *kModifyString="123 %1 456";

QString s = QString( kModifyString ).arg( sampleString );
char xx[ 1000 ];
strcpy( xx, s.toAscii().constData() );

and here is a result:
http://imagehost.spark-media.ru/i/80CB688A-3E79-FB8E-2038-39D20696F708.png
you see, that xx[ 10 ] equals 10, that is a new line

kokilakr
17th June 2010, 16:11
Hello,
Thanks for snippet. The .arg takes string with newline.
But the evaluateJavaScript needs it to specify as \\n instead of \n. But I am unaware of what all the characters my string can contain.
So I want to escape the newline and similiar characters. Any help regarding this.

borisbn
17th June 2010, 17:20
You can escape the string, passing to eval function like this


QString scriptString = QString(kModifyString).arg(sampleString);
scriptString.replace( "\n", "\\n" );
webFrame->evaluateJavaScript( scriptString );

numbat
17th June 2010, 17:28
You will also have to do:
\r
\"
\\

borisbn
17th June 2010, 17:54
By the way (sorry for using alient thread to ask) is there any C++ libraries, provided standard (un)escape functions?
I needed (right form of need in past? ) it to save/load some not simple strings in ini-file.

numbat
18th June 2010, 11:47
QString escapeJavascriptString(const QString & str)
{
QString out;
QRegExp rx("(\\r|\\n|\\\\|\")");
int pos = 0, lastPos = 0;

while ((pos = rx.indexIn(str, pos)) != -1)
{
out += str.mid(lastPos, pos - lastPos);

switch (rx.cap(1).at(0).unicode())
{
case '\r':
out += "\\r";
break;
case '\n':
out += "\\n";
break;
case '"':
out += "\\\"";
break;
case '\\':
out += "\\\\";
break;
}
pos++;
lastPos = pos;
}
out += str.mid(lastPos);
return out;
}

kokilakr
24th June 2010, 09:09
Thanks for everyone.
It worked.
First, I need to escape with \\ and then others.