Escaping a string for Javascript

Hi!
I've been using a lot of time on how to escape special characters in order for Javascript to accept a string. It seems like I need to escape single quotes, double quotes, backslash and newline.
I've written some code, but I just can't get it to work.
public static String editorSafeFilter(String text)
        if(text == null){
            return null;
        StringBuffer buffer = new StringBuffer(text.length());
         for (int i = 0; i < text.length(); i++) {
            char ch = text.charAt(i);
             switch (ch) {
               case 10: // '\n'
                    buffer.append(" ");
                    break;
                case 13:
                     buffer.append(" ");     // '\r'
                     break;
                case '\'':
                    buffer.append('\\');
                    buffer.append("\'");
                    break;
                case '"':
                    buffer.append('\\');
                    buffer.append('\"');
                    break;
                case '\\':
                    buffer.append('\\');
                    buffer.append('\\');
                    break;
                default :
                    buffer.append(ch);
                    break;
        return buffer.toString();
    }Anyone have any links or sample code that works?
thanks!
Vidar

It looks like you want the actual escape sequences... public static String editorSafeFilter(String text)
        if(text == null){
            return null;
        StringBuffer buffer = new StringBuffer(text.length());
         for (int i = 0; i < text.length(); i++) {
            char ch = text.charAt(i);
             switch (ch) {
               case '\012': // '\n'
                    buffer.append("\\n");     // '\n'
                    break;
                case '\015':
                    buffer.append("\\r");     // '\r'
                    break;
                case '\'':
                    buffer.append("\\\'");
                    break;
                case '\"':
                    buffer.append("\\\"");
                    break;
                case '\\':
                    buffer.append("\\\\");
                    break;
                default :
                    buffer.append(ch);
                    break;
        return buffer.toString();
    }

Similar Messages

  • How to decode encoded string for javascript

    This is encoded HTML code to be used at javascript function
    <div class=\"ProductDetail\"><div style=\"width:780px\">\r\n\t<div class=\"baslik\" style=\"margin: 0px; padding: 5px 10px; border-width: 5px 0px 1px; border-top-style: solid; border-bottom-style: solid; border-top-color: rgb(255, 255, 255); border-bottom-color: rgb(153, 165, 165); vertical-align: baseline; color: rgb(0, 0, 0); clear: both; line-height: 14px; font-family: 'Lucida Grande', sans-serif; font-size: 12px; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; orphans: auto; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; widows: auto; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(219, 223, 226);\"> Di\u011fer \u00d6zellikler<\/div><\/div><\/div>
    When decoded properly it becomes below
    <div class="ProductDetail"><div style="width:780px">
    <div class="baslik" style="margin: 0px; padding: 5px 10px; border-width: 5px 0px 1px; border-top-style: solid; border-bottom-style: solid; border-top-color: rgb(255, 255, 255); border-bottom-color: rgb(153, 165, 165); vertical-align: baseline; color: rgb(0, 0, 0); clear: both; line-height: 14px; font-family: 'Lucida Grande', sans-serif; font-size: 12px; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; orphans: auto; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; widows: auto; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(219, 223, 226);"> Diğer Özellikler</div></div></div>
    This website has both decode and encode features
    http://www.freeformatter.com/javascript-escape.html#ad-output
    I could find HttpUtility.JavaScriptStringEncode at c# however i couldn't find any function class etc to decode encoded string
    So i need help about how to decode like that website does
    .net 4.5 c#
    Browser based Pokemon Style MMORPG Game Developer Used asp.net 4.0 routing at it's
    Monsters

    Hi
    Monster,
    For web questions related to ASP.NET use the
    ASP.NET forum
    You should get more, better and faster answers on the other forum.  Thanks, ahead of time.
    Thanks
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Struts internalization for javascript messages

    Hi ALL,
    I am doing an internalization to my struts application... i am using property files for each language (say for example, english, french.. etc,) ... i can get the labels, messages to the struts fields, other texts..
    but how to interact the javascript messages? i don't know how to implement those messages for javascript...,
    please advise me
    Thanks
    Logu

    The javascript message is just template text printed onto the page right?
    So how is it different in concept from any other label?
    You may need to escape the messages for javascript (quotes etc etc) but on the whole you can apply the same i18n principles as you do elsewhere.
    ie
    // instead of this
    <script>
    alert('You did a bad thing');
    </script>
    // something like this
    <script>
    alert('<fmt:message key="badThing"/>');
    </script>

  • ReplaceAll / regexp / escaping a string

    Hi, I have a question about escaping a string for use with replaceAll. My objective is to replace all instances of string1 with string2 so I have been doing so using replaceAll. This works well however with it relying on regexp's I have some questions about escaping.
    I want to, for example, replace [%PARAM%] with '100%' however this starts to get in to the murky (to me) worlf of regular expressions. After some testing I realize I have lots of characters that are important to the regexp and I can avoid problems by escaping them like this:
    \\[\\%PARAM\\%\\] with '100\\%'
    This works however the values will be parsed out of strings the user enters so clearly I don't want them to have to add the escape characters, is there a way I can:
    a) Tell it to ignore special characters so it is treated like a basic searcha nd replace or
    b) Autmatically escape any problematic characters in the string before calling replaceAll?
    If there is another approach you would recommend I'd be very interested to hear it too.
    Thanks in advance,
    Chris.

    Don't get me started on the evils of writing Java inside JSP!
    Anyway, if you look at the documentation I helpfully linked for you, you'll see that the replace method that can take two Strings (two CharSequences to be precise) versus just two chars was introduced in version 1.5, so you must be using an older compiler.
    You should consider upgrading to 1.6. Even 1.5, let alone the version you must be using, is in its Java Technology End of Life (EOL) transition period.
    [http://java.sun.com/javase/downloads/index_jdk5.jsp]

  • Escape XML Strings with JDK class

    Hi,
    can anyone tell me how to escape XML-Strings with classes of the JDK?
    When searching I only was pointed to StringEscapeUtils from apache.commons.lang, but we would prefer to use the JDK instead of integrating an external lib.
    Our aim is to escape an XML attribute, so a CDATA is not applicable for us in this case.
    Thanks
    Jan

    I implemented it by myself:
    public static String escapeXmlAttribute(String attributeValue) {
            StringBuffer result = new StringBuffer();
            for (int c = 0; c < attributeValue.length(); ++c) {
                if (attributeValue.charAt(c) == '"') {
                    result.append("&#34;");
                } else if (attributeValue.charAt(c) == '&') {
                    result.append("&#38;");
                } else if (attributeValue.charAt(c) == '<') {
                    result.append("<");
                } else if (attributeValue.charAt(c) == '>') {
                    result.append(">");
                } else {
                    result.append(attributeValue.charAt(c));
            return result.toString();
        }{code}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • [svn:bz-trunk] 11030: Tweak the deserialization of ASObjects to treat an empty string for the type of an object as null .

    Revision: 11030
    Author:   [email protected]
    Date:     2009-10-20 11:35:02 -0700 (Tue, 20 Oct 2009)
    Log Message:
    Tweak the deserialization of ASObjects to treat an empty string for the type of an object as null. It appears that there is some logic in the LC remoting code that relies on a non-null class name to always exist. This change reverts to the old behavior of not allowing empty string as a value for the ASObject.namedType.
    This should fix bug 2448442 and its duplicates caused by the recent serialization changes.
    I don't think this is the perfect fix. Pending further investigation, a better fix would be either:
    a. If it's OK to assume that empty string should always mean null for the type of the ASObject, the code that enforces it should be in the setter/getter inside ASObject and not in the deserializer.
    b. ASObject doesn't guarantee that a named type exists or is valid. In that sense an empty string is as bad as some random characters that cannot be a valid class name in java, so depending on how disruptive it may be, the fix should be in any logic that uses ASObject.getType().
    Modified Paths:
        blazeds/trunk/modules/core/src/flex/messaging/io/amf/AbstractAmfInput.java

    Hi Pavan,
    "In your payload there is no namespace prefix for the elements under PayloadHeader element."
    Yes, you are right - but this message is standard AQ Adapter Header message - it's not defined by me. I just used message which was automatically added to my project when I have defined AQ Adapter.
    "In your process is the default namespace is same as namespace value of tns ??"
    Do you mean targetNamespace? If yes it's different as it points to process "targetNamespace="http://xmlns.oracle.com/PF_SOA_jws/PF_APPS/APPS_PROCESS" (names of application and process have changed as I try different ways to do that)
    ns1 is: xmlns:ns1="http://xmlns.oracle.com/pcbpel/adapter/aq/PF_SOA/PF_APPS/PO_AQ"
    "another thing is tns and ns1 should have same values.."
    When I create a variable of header type, namespace ns1 is automatically created for it. I set it as property of receive activity. When process is instantiated on the serwer I get the error in which you can see that namespace is tns.
    Maybe I'm doing something wrong but I don't see how I could fix this in my process.
    You can see that the message I get on the server has nothing in common with the application/project/process names. Is it possible to define such variable?
    Regards
    Pawel
    PS:
    In Transformation xsl file, both variables (source and target) has tns namespace for Header and PayloadHeader, and no namespace for subfields.
    Edited by: pawel.fidelus on 2010-01-05 02:37

  • How to dynamically set connection string for report in C# code?

    Hi,
    I have installed CRVS2010. I have created new Crystal Report WPF Application and new report. I would like to set connection string for report in code dynamically.
    Is this possible?
    Thanks
    Ivana

    Lots of posts in this forum on how to set database connections. WPF should not be a consideration as it's just a viewer. The report engine is still the same. Search these forums. Use the search box at the top right corner of this page. Look at samples here:
    https://wiki.sdn.sap.com/wiki/display/BOBJ/CrystalReportsfor.NETSDK+Samples
    Note that none of the samples above are using WPF, but like I said, the WPF is just a different viewer and will not impact how the report engine logs on to a database. (I think of it as a gray car vs. a red car. Same engine, just the color is different)
    Ludek
    Follow us on Twitter http://twitter.com/SAPCRNetSup
    Got Enhancement ideas? Try the [SAP Idea Place|https://ideas.sap.com/community/products_and_solutions/crystalreports]

  • How to use multiple VCI strings for lap 1300 and 1200 (option 60) in one pool?

    Hi All,
    Hope to you a very happy new year,
    I have two differnt LAP 1300 and 1200 in my network and I need to add theme to the WLC,
    I successed to add one of theme by the option 60 in the DHCP pool at the Core SW,
    So my quetion is below:
    How to use multiple VCI strings for lap 1300 and 1200 (option 60) in one pool?
    Thanks in Advanced,
    Ahmed,

    To add to Scott's post.  Option 60 would be useful if you needed to put certain types of AP on specific controllers.  Otherwise, no real need to use it for the most part.
    Though, I do recall an issue a few years ago that some windows machines had issues getting DHCP if option 43 is being returned.
    Now, on an IOS switch, you can only configure one option 60 per DHCP scope
    HTH,
    Steve
    Please remember to rate useful posts, and mark questions as answered

  • Creation of input string for SHA-1 in hash total calculation

    In order to create an input string for the SHA-1 algorithm based on the REGUH table I am searching for the ABAP source code which can be used in the user exit of transaction of transaction F110 (Payment Run).
    Can anybody provide me the source code or is there a BAPI or something ?
    Please help. The problem is urgent and my ABAP engineer did not succeed so far developing the solution.
    Best regards, Edwin

    And this will get a base64 encoded hash
    select utl_raw.cast_to_varchar2( utl_encode.base64_encode( dbms_crypto.hash(utl_raw.cast_to_raw('mypass'),3) ) )
    from dual;

  • [svn] 3519: Fix typo in error string for situations where there are advanced messaging configuration settings from LCDS used in the configuration files but no AdvancedMessagingSupport service .

    Revision: 3519
    Author: [email protected]
    Date: 2008-10-08 04:17:40 -0700 (Wed, 08 Oct 2008)
    Log Message:
    Fix typo in error string for situations where there are advanced messaging configuration settings from LCDS used in the configuration files but no AdvancedMessagingSupport service. The error string said that there was no flex.messaging.services.AdvancedMessagingService registered but it is the flex.messaging.services.AdvancedMessagingSupport service that needs to be registered.
    Add configuration test that starts the server with a destination that has the reliable property set which is an advanced messaging feature but there is no AdvancedMessagingSupport service registered.
    Modified Paths:
    blazeds/trunk/modules/common/src/flex/messaging/errors.properties
    Added Paths:
    blazeds/trunk/qa/apps/qa-regress/testsuites/config/tests/messagingService/ReliableDestina tionWithNoAdvancedMessagingSupport/
    blazeds/trunk/qa/apps/qa-regress/testsuites/config/tests/messagingService/ReliableDestina tionWithNoAdvancedMessagingSupport/error.txt
    blazeds/trunk/qa/apps/qa-regress/testsuites/config/tests/messagingService/ReliableDestina tionWithNoAdvancedMessagingSupport/services-config.xml

    Hi,
    Unfortunately I already tried all kinds of re-installs (the full list is in my original message). The only one remaining is the reinstall of Windows 8 itself, which I would really like to avoid.
    What I find really strange is the time it takes for the above error message to appear. It's like one hour or even more (never measured exactly, I left the computer running).
    What kind of a timeout is that? I would expect that, if ports are really used by some other application, I get the message in less than a minute (seconds, actually). To me this looks like the emulator itself for some reason believes there's a problem with
    some port while in reality there isn't.
    I'll eventually contact Microsoft Support, thanks for the suggestion.

  • Define Search String for EBS in SAP 4.6c

    Hi All,
    I have some question for search string for EBS in SAP 4.6c. I have already done this thing in ECC 6 and work well with "target field" as account number. but in 4.6c target field account number doesn't exist. Please suggest me, if there is a same way like account number target field in 4.6c?
    Thanks in advance
    Glenn

    Hi Shanumonu,
    Thx for the answer, you save my life!
    But I have another issued. I already implement SE11 instruction, but item with wrong note to payee number from MT940 keep cleared. Do you have suggestion for me?
    Thanks,
    Glenn

  • Show Error string for all the components in a form at a time

    How do I show all the error strings for all the components in the form when the submit button is clicked?

    This code answers your question:
    <?xml version="1.0"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
      <mx:Script>
        <![CDATA[
          import mx.events.ValidationResultEvent;
          import mx.validators.ZipCodeValidator;
          import flash.events.MouseEvent;
          public var v:ZipCodeValidator = new ZipCodeValidator();
          public var vResult:ValidationResultEvent;
          public function performValidation():void {
            v.domain = "US or Canada";
            v.listener=myZip;
            vResult = v.validate(myZip.text);
            if (vResult.type==ValidationResultEvent.INVALID) {
              myZip.dispatchEvent(new MouseEvent(MouseEvent.MOUSE_OUT));            
              myZip.dispatchEvent(new MouseEvent(MouseEvent.MOUSE_OVER));
        ]]>
      </mx:Script>
      <mx:TextInput id="myZip"/>
      <mx:Button label="Submit" click="performValidation();"/>
    </mx:Application>
    If this post answers your question or helps, please mark it as such. Thanks!
    http://www.stardustsystems.com
    http://www.stardustsystems.com/blog
    Adobe Flex Development and Support Services

  • Save Query - An error occurred while creating connection strings for the query

    A workbook trying to edit and reload I get the following error "Save Query - An error occurred while creating connection strings for the query" No Power Pivot data model or anything.

    I am getting the same error when editing a Power Query in an Excel spreadsheet. It happens when I change a Group By step to do a Sum instead of Count Rows.

  • VISA and Scan string for tokens

    Hi there,
    I am currently developing a piece of software which needs to take in data from an Arduino board via the serial port and parse the input accordingly.
    I have the 2 pieces of code working perfectly well separately, but I can not seem to figure out why they are not functioning properly together.
    Just now, the input is being retrieved fine and passed into the Scan string for tokens method, but it is not being split on the tokens, it is just outputting the string as a whole.
    The input is in the form of 1:0 2:0 3:1 etc. so I am trying to split it on any spaces found.  If I attach a string to the Scan strings for tokens it works fine, just not when I am attaching the data from the serial port to it.
    Any help would be appreciated.
    Attachments:
    input manipulation.vi ‏16 KB

    Hi,
    In the output which you are getting from the serial port, is there space between 1:0 and 2:0 and 3:1? If there is no space between them, then it wont be able to scan for tokens and will output the whole string. I don't have the hardware here and so don't know what exactly is the output which you are receiving. Try to see in the read buffer indicator whether the tokens are seperated by a space or not.
    I have attached your vi after adding a small part in it. If the problem is with the spacing then this will work fine for 1:0 2:0 3:1.
    Regards,
    Nitzz
    (Give kudos to good Answers , Mark it as a Solution if your problem is Solved) 
    Attachments:
    input manipulation.vi ‏18 KB

  • What's SAP Router String for?

    Hi,
    I can not find proper module for me to post this message, so I post it here.
    When we create a new item in the SAP logon screen , we need to specify the following parameters:
    1) System description
    2) Message server
    3) SAP Router String (optional)
    4) System ID
    5) System Number
    4) Group
    My question is, what's SAP router string for? How to define a new SAP router string?
    Because sometimes we don't need to input SAP router string, and we can still logon to the system successfully.
    So, If I need to create a new SAP router string, where to define?
    Thanks.

    Hi
    A route string describes the stations of a connection required between two hosts. A route string has the syntax
    (/H/host/S/service/W/pass)*
    It consists of any number of substrings in the form /H/host/S/service/W/pass .
    A route string contains a substring for each SAProuter and for the target server.
    Each substring contains the information required by SAProuter to set up a connection in the route: the host name, the port name, and the password, if one was given.
    Syntax for substrings:
    ·        /H / indicates the host name‑{}‑
    Note that the host name must be at least two characters long.
    ·        /S/ is used for specifying the service (port); it is an optional entry, the default value is 3299
    ·        /W/ indicates the password for the connection between the predecessor and successor on the route and is also optional (default is u201Cu201D, no password)
    In earlier Releases (<4.0A), the password entry was made one substring later and with the letter /P/.
    New: /H/saprouter/W/pass/H/targetserver
    Old: /H/saprouter/H/targetserver/P/pass
    (Here pass is the password which is checked by the SAProuter on host saprouter to set up or prohibit the connection from the source host to the target host.)
    Due to downward compatibility, the old password entry form is still possible.
    Thenaks & Regards
    Kishore

Maybe you are looking for

  • Source system problem.

    Hello All, I Transported the Request BWD To BWQ but request ennded with errors i collected all the objects Message no. RSAR409 Diagnosis Source system ZDBREMEDY is not known. System Response The imported data for DataSource  was deleted again because

  • Iphone 5s background photo uploading broken?

    I just got the Iphone 5s and I have tried the Flickr app and the Google+ app.  Neither of them upload my photos until I go to the actual app.  Even if they are running in the background they don't auto upload.  Is that normal?  Thanks.

  • BT Infinity - IP address at Router.

    This question relates to the Internet side of my BT Infinity connection. Does any one know if BT setup Static TCP/IP or use DHCP? If they use DHCP what is the lease time ? I know that I have DHCP running on my LAN side.

  • Safari won't open word documents

    Recently, Safari won't open any word documents or pdf. Any suggestions? The error message says there are no available programs to open it. Although Pages is installed. Thanks!

  • Print data to the beginning of a file

    Hi, I have written this code to wite data to a textfile: PrintWriter FeedStream = new PrintWriter(new FileOutputStream(feed_path, true)); FeedStream.println(text); FeedStream.close();The code works fine but it writes the data at the end of the file w