| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134 |
- //
- // NSString+RAJavascript.m
- // APEX CRM
- //
- // Created by Jack on 2018/12/1.
- // Copyright © 2018年 USAI. All rights reserved.
- //
- #import "NSString+RAJavascript.h"
- @implementation NSString (RAJavascript)
- - (unsigned char)ra_hexCharFromInt:(int)value
- {
- if (value <= 9) return (unsigned char)(value + 48);
- return (unsigned char)((value - 10) + 97);
- }
- - (NSString *)ra_unicodeStringForChar:(unichar)ch
- {
- unsigned char uni[] = {
- [self ra_hexCharFromInt:((ch >> 12) & 0x0f)],
- [self ra_hexCharFromInt:((ch >> 8) & 0x0f)],
- [self ra_hexCharFromInt:((ch >> 4) & 0x0f)],
- [self ra_hexCharFromInt:(ch & 0x0f)],
- 0
- };
- return [NSString stringWithUTF8String:(char*)uni];
- }
- - (NSString *)ra_stringByEscapingForJavascriptWithDelimiter:(unichar)delimiter wrapWithDelimiters:(BOOL)wrap
- {
- NSMutableString *js = [[NSMutableString alloc] init];
-
- if (wrap)
- {
- [js appendFormat:@"%C", delimiter];
- }
-
- int lastWritePosition = 0;
- int skipped = 0;
- NSInteger length = self.length;
- unichar *chars = malloc(sizeof(unichar) * length);
- unichar c;
- [self getCharacters:chars range:NSMakeRange(0, length)];
- NSString *escapedValue;
-
- for (int i = 0; i < length; i++)
- {
- c = chars[i];
-
- switch (c)
- {
- case L'\t':
- escapedValue = @"\\t";
- break;
- case L'\n':
- escapedValue = @"\\n";
- break;
- case L'\r':
- escapedValue = @"\\r";
- break;
- case L'\f':
- escapedValue = @"\\f";
- break;
- case L'\b':
- escapedValue = @"\\b";
- break;
- case L'\\':
- escapedValue = @"\\\\";
- break;
- case 0x0085:
- escapedValue = @"\\u0085";
- break;
- case 0x2028:
- escapedValue = @"\\u2028";
- break;
- case 0x2029:
- escapedValue = @"\\u2029";
- break;
- case L'\'':
- escapedValue = (delimiter == L'\'') ? @"\\'" : nil;
- break;
- case L'"':
- escapedValue = (delimiter == '"') ? @"\\\"" : nil;
- break;
- default:
- escapedValue = (c <= 0x001f) ? [self ra_unicodeStringForChar:c] : nil;
- break;
- }
-
- if (escapedValue)
- {
- if (skipped > 0)
- {
- [js appendString:[self substringWithRange:NSMakeRange(lastWritePosition, skipped)]];
- skipped = 0;
- }
-
- [js appendString:escapedValue];
- lastWritePosition = i + 1;
- }
- else
- {
- skipped++;
- }
- }
-
- if (skipped > 0)
- {
- if (lastWritePosition == 0)
- {
- [js appendString:self];
- }
- else
- {
- [js appendString:[self substringWithRange:NSMakeRange(lastWritePosition, skipped)]];
- }
- }
-
- free(chars);
-
- if (wrap)
- {
- [js appendFormat:@"%C", delimiter];
- }
-
- return js;
- }
- @end
|