Java String Sanitize sanitizeIdentifierName(String input)

Here you can find the source of sanitizeIdentifierName(String input)

Description

Escapes illegal characters in given identifier.

License

Open Source License

Declaration

public static String sanitizeIdentifierName(String input) 

Method Source Code

//package com.java2s;
/**//ww  w.java  2 s . c  o  m
 * Copyright (c) 2016 NumberFour AG.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *   NumberFour AG - Initial API and implementation
 */

public class Main {
    /**
     * Escapes illegal characters in given identifier. Used for function names, etc.
     */
    public static String sanitizeIdentifierName(String input) {
        if (input == null || input.isEmpty()) {
            return input;
        }
        final StringBuilder result = new StringBuilder();
        char ch = input.charAt(0);
        if (Character.isJavaIdentifierStart(ch)) {
            result.append(ch);
        } else {
            result.append("_" + Character.codePointAt(input, 0) + "$");
        }
        int i = 1;
        while (i < input.length()) {
            ch = input.charAt(i);
            if (Character.isJavaIdentifierPart(ch)) {
                result.append(ch);
            } else {
                result.append("_" + Character.codePointAt(input, i) + "$");
            }
            i = i + 1;
        }
        return result.toString();
    }
}

Related

  1. sanitizeFullPrefixKey(String propKey)
  2. sanitizeGoogleId(String rawGoogleId)
  3. sanitizeHeader(String header)
  4. sanitizeID(String name)
  5. sanitizeIdentifier(String identifier)
  6. sanitizeIDs(String str)
  7. sanitizeInput(String input)
  8. sanitizeInput(String string)
  9. sanitizeJavascript(String originalString)