Class: String

Inherits:
Object
  • Object
show all
Includes:
Comparable
Defined in:
opal/opal/corelib/string.rb,
opal/opal/corelib/string/inheritance.rb

Defined Under Namespace

Classes: Wrapper

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Comparable

#<, #<=, #>, #>=, #between?, normalize

Class Method Details

.inherited(klass) ⇒ Object



2
3
4
5
6
7
8
9
10
11
12
13
14
# File 'opal/opal/corelib/string/inheritance.rb', line 2

def self.inherited(klass)
  replace = Class.new(String::Wrapper)

  %x{
    klass._proto        = replace._proto;
    klass._proto._klass = klass;
    klass._alloc        = replace._alloc;
    klass.__parent      = #{String::Wrapper};

    klass.$allocate = replace.$allocate;
    klass.$new      = replace.$new;
  }
end

.new(str = '') ⇒ Object



14
15
16
# File 'opal/opal/corelib/string.rb', line 14

def self.new(str = '')
  `new String(str)`
end

.try_convert(what) ⇒ Object



8
9
10
11
12
# File 'opal/opal/corelib/string.rb', line 8

def self.try_convert(what)
  what.to_str
rescue
  nil
end

Instance Method Details

#%(data) ⇒ Object



18
19
20
21
22
23
24
# File 'opal/opal/corelib/string.rb', line 18

def %(data)
  if Array === data
    format(self, *data)
  else
    format(self, data)
  end
end

#*(count) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'opal/opal/corelib/string.rb', line 26

def *(count)
  %x{
    if (count < 1) {
      return '';
    }

    var result  = '',
        pattern = self;

    while (count > 0) {
      if (count & 1) {
        result += pattern;
      }

      count >>= 1;
      pattern += pattern;
    }

    return result;
  }
end

#+(other) ⇒ Object



48
49
50
51
52
# File 'opal/opal/corelib/string.rb', line 48

def +(other)
  other = Opal.coerce_to other, String, :to_str

  `self + #{other.to_s}`
end

#<=>(other) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'opal/opal/corelib/string.rb', line 54

def <=>(other)
  if other.respond_to? :to_str
    other = other.to_str.to_s

    `self > other ? 1 : (self < other ? -1 : 0)`
  else
    %x{
      var cmp = #{other <=> self};

      if (cmp === nil) {
        return nil;
      }
      else {
        return cmp > 0 ? -1 : (cmp < 0 ? 1 : 0);
      }
    }
  end
end

#==(other) ⇒ Object Also known as: eql?, ===



73
74
75
76
77
# File 'opal/opal/corelib/string.rb', line 73

def ==(other)
  return false unless String === other

  `#{to_s} == #{other.to_s}`
end

#=~(other) ⇒ Object



82
83
84
85
86
87
88
89
90
# File 'opal/opal/corelib/string.rb', line 82

def =~(other)
  %x{
    if (other._isString) {
      #{raise TypeError, 'type mismatch: String given'};
    }

    return #{other =~ self};
  }
end

#[](index, length = undefined) ⇒ Object Also known as: slice



92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
# File 'opal/opal/corelib/string.rb', line 92

def [](index, length = undefined)
  %x{
    var size = self.length;

    if (index._isRange) {
      var exclude = index.exclude,
          length  = index.end,
          index   = index.begin;

      if (index < 0) {
        index += size;
      }

      if (length < 0) {
        length += size;
      }

      if (!exclude) {
        length += 1;
      }

      if (index > size) {
        return nil;
      }

      length = length - index;

      if (length < 0) {
        length = 0;
      }

      return self.substr(index, length);
    }

    if (index < 0) {
      index += self.length;
    }

    if (length == null) {
      if (index >= self.length || index < 0) {
        return nil;
      }

      return self.substr(index, 1);
    }

    if (index > self.length || index < 0) {
      return nil;
    }

    return self.substr(index, length);
  }
end

#capitalizeObject



146
147
148
# File 'opal/opal/corelib/string.rb', line 146

def capitalize
  `self.charAt(0).toUpperCase() + self.substr(1).toLowerCase()`
end

#casecmp(other) ⇒ Object



150
151
152
153
154
# File 'opal/opal/corelib/string.rb', line 150

def casecmp(other)
  other = Opal.coerce_to(other, String, :to_str).to_s

  `self.toLowerCase()` <=> `other.toLowerCase()`
end

#center(width, padstr = ' ') ⇒ Object



156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# File 'opal/opal/corelib/string.rb', line 156

def center(width, padstr = ' ')
  width  = Opal.coerce_to(width, Integer, :to_int)
  padstr = Opal.coerce_to(padstr, String, :to_str).to_s

  if padstr.empty?
    raise ArgumentError, 'zero width padding'
  end

  return self if `width <= self.length`

  %x{
    var ljustified = #{ljust ((width + @length) / 2).ceil, padstr},
        rjustified = #{rjust ((width + @length) / 2).floor, padstr};

    return rjustified + ljustified.slice(self.length);
  }
end

#chars(&block) ⇒ Object



174
175
176
177
178
# File 'opal/opal/corelib/string.rb', line 174

def chars(&block)
  return each_char.to_a unless block

  each_char(&block)
end

#chomp(separator = $/) ⇒ Object



180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
# File 'opal/opal/corelib/string.rb', line 180

def chomp(separator = $/)
  return self if `separator === nil || self.length === 0`

  separator = Opal.coerce_to!(separator, String, :to_str).to_s

  %x{
    if (separator === "\n") {
      return self.replace(/\r?\n?$/, '');
    }
    else if (separator === "") {
      return self.replace(/(\r?\n)+$/, '');
    }
    else if (self.length > separator.length) {
      var tail = self.substr(self.length - separator.length, separator.length);

      if (tail === separator) {
        return self.substr(0, self.length - separator.length);
      }
    }
  }

  self
end

#chopObject



204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
# File 'opal/opal/corelib/string.rb', line 204

def chop
  %x{
    var length = self.length;

    if (length <= 1) {
      return "";
    }

    if (self.charAt(length - 1) === "\n" && self.charAt(length - 2) === "\r") {
      return self.substr(0, length - 2);
    }
    else {
      return self.substr(0, length - 1);
    }
  }
end

#chrObject



221
222
223
# File 'opal/opal/corelib/string.rb', line 221

def chr
  `self.charAt(0)`
end

#cloneObject Also known as: dup



225
226
227
228
229
# File 'opal/opal/corelib/string.rb', line 225

def clone
  copy = `self.slice()`
  copy.initialize_clone(self)
  copy
end

#count(str) ⇒ Object



237
238
239
# File 'opal/opal/corelib/string.rb', line 237

def count(str)
  `(self.length - self.replace(new RegExp(str, 'g'), '').length) / str.length`
end

#downcaseObject



243
244
245
# File 'opal/opal/corelib/string.rb', line 243

def downcase
  `self.toLowerCase()`
end

#each_char(&block) ⇒ Object



247
248
249
250
251
252
253
254
255
256
257
# File 'opal/opal/corelib/string.rb', line 247

def each_char(&block)
  return enum_for :each_char unless block_given?

  %x{
    for (var i = 0, length = self.length; i < length; i++) {
      #{yield `self.charAt(i)`};
    }
  }

  self
end

#each_line(separator = $/) ⇒ Object



259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
# File 'opal/opal/corelib/string.rb', line 259

def each_line(separator = $/)
  return split(separator) unless block_given?

  %x{
    var chomped  = #{chomp},
        trailing = self.length != chomped.length,
        splitted = chomped.split(separator);

    for (var i = 0, length = splitted.length; i < length; i++) {
      if (i < length - 1 || trailing) {
        #{yield `splitted[i] + separator`};
      }
      else {
        #{yield `splitted[i]`};
      }
    }
  }

  self
end

#empty?Boolean

Returns:



280
281
282
# File 'opal/opal/corelib/string.rb', line 280

def empty?
  `self.length === 0`
end

#end_with?(*suffixes) ⇒ Boolean

Returns:



284
285
286
287
288
289
290
291
292
293
294
295
296
297
# File 'opal/opal/corelib/string.rb', line 284

def end_with?(*suffixes)
  %x{
    for (var i = 0, length = suffixes.length; i < length; i++) {
      var suffix = #{Opal.coerce_to(`suffixes[i]`, String, :to_str).to_s};

      if (self.length >= suffix.length &&
          self.substr(self.length - suffix.length, suffix.length) == suffix) {
        return true;
      }
    }
  }

  false
end

#freezeObject



1188
1189
1190
# File 'opal/opal/corelib/string.rb', line 1188

def freeze
  self
end

#frozen?Boolean

Returns:



1192
1193
1194
# File 'opal/opal/corelib/string.rb', line 1192

def frozen?
  true
end

#gsub(pattern, replace = undefined, &block) ⇒ Object



302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
# File 'opal/opal/corelib/string.rb', line 302

def gsub(pattern, replace = undefined, &block)
  if String === pattern || pattern.respond_to?(:to_str)
    pattern = /#{Regexp.escape(pattern.to_str)}/
  end

  unless Regexp === pattern
    raise TypeError, "wrong argument type #{pattern.class} (expected Regexp)"
  end

  %x{
    var pattern = pattern.toString(),
        options = pattern.substr(pattern.lastIndexOf('/') + 1) + 'g',
        regexp  = pattern.substr(1, pattern.lastIndexOf('/') - 1);

    self.$sub._p = block;
    return self.$sub(new RegExp(regexp, options), replace);
  }
end

#hashObject



321
322
323
# File 'opal/opal/corelib/string.rb', line 321

def hash
  `self.toString()`
end

#hexObject



325
326
327
# File 'opal/opal/corelib/string.rb', line 325

def hex
  to_i 16
end

#include?(other) ⇒ Boolean

Returns:



329
330
331
332
333
334
335
336
337
338
339
340
341
# File 'opal/opal/corelib/string.rb', line 329

def include?(other)
  %x{
    if (other._isString) {
      return self.indexOf(other) !== -1;
    }
  }

  unless other.respond_to? :to_str
    raise TypeError, "no implicit conversion of #{other.class.name} into String"
  end

  `self.indexOf(#{other.to_str}) !== -1`
end

#index(what, offset = nil) ⇒ Object



343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
# File 'opal/opal/corelib/string.rb', line 343

def index(what, offset = nil)
  if String === what
    what = what.to_s
  elsif what.respond_to? :to_str
    what = what.to_str.to_s
  elsif not Regexp === what
    raise TypeError, "type mismatch: #{what.class} given"
  end

  result = -1

  if offset
    offset = Opal.coerce_to offset, Integer, :to_int

    %x{
      var size = self.length;

      if (offset < 0) {
        offset = offset + size;
      }

      if (offset > size) {
        return nil;
      }
    }

    if Regexp === what
      result = (what =~ `self.substr(offset)`) || -1
    else
      result = `self.substr(offset).indexOf(what)`
    end

    %x{
      if (result !== -1) {
        result += offset;
      }
    }
  else
    if Regexp === what
      result = (what =~ self) || -1
    else
      result = `self.indexOf(what)`
    end
  end

  unless `result === -1`
    result
  end
end

#inspectObject



393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
# File 'opal/opal/corelib/string.rb', line 393

def inspect
  %x{
    var escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        meta      = {
          '\b': '\\b',
          '\t': '\\t',
          '\n': '\\n',
          '\f': '\\f',
          '\r': '\\r',
          '"' : '\\"',
          '\\': '\\\\'
        };

    escapable.lastIndex = 0;

    return escapable.test(self) ? '"' + self.replace(escapable, function(a) {
      var c = meta[a];

      return typeof c === 'string' ? c :
        '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
    }) + '"' : '"' + self + '"';
  }
end

#internObject Also known as: to_sym



417
418
419
# File 'opal/opal/corelib/string.rb', line 417

def intern
  self
end

#lengthObject Also known as: size



425
426
427
# File 'opal/opal/corelib/string.rb', line 425

def length
  `self.length`
end

#lines(separator = $/) ⇒ Object



421
422
423
# File 'opal/opal/corelib/string.rb', line 421

def lines(separator = $/)
  each_line(separator).to_a
end

#ljust(width, padstr = ' ') ⇒ Object



429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
# File 'opal/opal/corelib/string.rb', line 429

def ljust(width, padstr = ' ')
  width  = Opal.coerce_to(width, Integer, :to_int)
  padstr = Opal.coerce_to(padstr, String, :to_str).to_s

  if padstr.empty?
    raise ArgumentError, 'zero width padding'
  end

  return self if `width <= self.length`

  %x{
    var index  = -1,
        result = "";

    width -= self.length;

    while (++index < width) {
      result += padstr;
    }

    return self + result.slice(0, width);
  }
end

#lstripObject



453
454
455
# File 'opal/opal/corelib/string.rb', line 453

def lstrip
  `self.replace(/^\s*/, '')`
end

#match(pattern, pos = undefined, &block) ⇒ Object



457
458
459
460
461
462
463
464
465
466
467
# File 'opal/opal/corelib/string.rb', line 457

def match(pattern, pos = undefined, &block)
  if String === pattern || pattern.respond_to?(:to_str)
    pattern = /#{Regexp.escape(pattern.to_str)}/
  end

  unless Regexp === pattern
    raise TypeError, "wrong argument type #{pattern.class} (expected Regexp)"
  end

  pattern.match(self, pos, &block)
end

#nextObject Also known as: succ



469
470
471
472
473
474
475
476
477
478
479
480
# File 'opal/opal/corelib/string.rb', line 469

def next
  %x{
    if (self.length === 0) {
      return "";
    }

    var initial = self.substr(0, self.length - 1);
    var last    = String.fromCharCode(self.charCodeAt(self.length - 1) + 1);

    return initial + last;
  }
end

#ordObject



482
483
484
# File 'opal/opal/corelib/string.rb', line 482

def ord
  `self.charCodeAt(0)`
end

#partition(str) ⇒ Object



486
487
488
489
490
491
492
493
# File 'opal/opal/corelib/string.rb', line 486

def partition(str)
  %x{
    var result = self.split(str);
    var splitter = (result[0].length === self.length ? "" : str);

    return [result[0], splitter, result.slice(1).join(str.toString())];
  }
end

#reverseObject



495
496
497
# File 'opal/opal/corelib/string.rb', line 495

def reverse
  `self.split('').reverse().join('')`
end

#rindex(search, offset = undefined) ⇒ Object

TODO handle case where search is regexp



500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
# File 'opal/opal/corelib/string.rb', line 500

def rindex(search, offset = undefined)
  %x{
    var search_type = (search == null ? Opal.NilClass : search.constructor);
    if (search_type != String && search_type != RegExp) {
      var msg = "type mismatch: " + search_type + " given";
      #{raise TypeError.new(`msg`)};
    }

    if (self.length == 0) {
      return search.length == 0 ? 0 : nil;
    }

    var result = -1;
    if (offset != null) {
      if (offset < 0) {
        offset = self.length + offset;
      }

      if (search_type == String) {
        result = self.lastIndexOf(search, offset);
      }
      else {
        result = self.substr(0, offset + 1).$reverse().search(search);
        if (result !== -1) {
          result = offset - result;
        }
      }
    }
    else {
      if (search_type == String) {
        result = self.lastIndexOf(search);
      }
      else {
        result = self.$reverse().search(search);
        if (result !== -1) {
          result = self.length - 1 - result;
        }
      }
    }

    return result === -1 ? nil : result;
  }
end

#rjust(width, padstr = ' ') ⇒ Object



544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
# File 'opal/opal/corelib/string.rb', line 544

def rjust(width, padstr = ' ')
  width  = Opal.coerce_to(width, Integer, :to_int)
  padstr = Opal.coerce_to(padstr, String, :to_str).to_s

  if padstr.empty?
    raise ArgumentError, 'zero width padding'
  end

  return self if `width <= self.length`

  %x{
    var chars     = Math.floor(width - self.length),
        patterns  = Math.floor(chars / padstr.length),
        result    = Array(patterns + 1).join(padstr),
        remaining = chars - result.length;

    return result + padstr.slice(0, remaining) + self;
  }
end

#rstripObject



564
565
566
# File 'opal/opal/corelib/string.rb', line 564

def rstrip
  `self.replace(/\s*$/, '')`
end

#scan(pattern, &block) ⇒ Object



568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
# File 'opal/opal/corelib/string.rb', line 568

def scan(pattern, &block)
  %x{
    if (pattern.global) {
      // should we clear it afterwards too?
      pattern.lastIndex = 0;
    }
    else {
      // rewrite regular expression to add the global flag to capture pre/post match
      pattern = new RegExp(pattern.source, 'g' + (pattern.multiline ? 'm' : '') + (pattern.ignoreCase ? 'i' : ''));
    }

    var result = [];
    var match;

    while ((match = pattern.exec(self)) != null) {
      var match_data = #{MatchData.new `pattern`, `match`};
      if (block === nil) {
        match.length == 1 ? result.push(match[0]) : result.push(match.slice(1));
      }
      else {
        match.length == 1 ? block(match[0]) : block.apply(self, match.slice(1));
      }
    }

    return (block !== nil ? self : result);
  }
end

#split(pattern = $; || ' ', limit = undefined) ⇒ Object



600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
# File 'opal/opal/corelib/string.rb', line 600

def split(pattern = $; || ' ', limit = undefined)
  %x{
    if (pattern === nil || pattern === undefined) {
      pattern = #{$;};
    }

    var result = [];
    if (limit !== undefined) {
      limit = #{Opal.coerce_to!(limit, Integer, :to_int)};
    }

    if (self.length === 0) {
      return [];
    }

    if (limit === 1) {
      return [self];
    }

    if (pattern && pattern._isRegexp) {
      var pattern_str = pattern.toString();

      /* Opal and JS's repr of an empty RE. */
      var blank_pattern = (pattern_str.substr(0, 3) == '/^/') ||
                (pattern_str.substr(0, 6) == '/(?:)/');

      /* This is our fast path */
      if (limit === undefined || limit === 0) {
        result = self.split(blank_pattern ? /(?:)/ : pattern);
      }
      else {
        /* RegExp.exec only has sane behavior with global flag */
        if (! pattern.global) {
          pattern = eval(pattern_str + 'g');
        }

        var match_data;
        var prev_index = 0;
        pattern.lastIndex = 0;

        while ((match_data = pattern.exec(self)) !== null) {
          var segment = self.slice(prev_index, match_data.index);
          result.push(segment);

          prev_index = pattern.lastIndex;

          if (match_data[0].length === 0) {
            if (blank_pattern) {
              /* explicitly split on JS's empty RE form.*/
              pattern = /(?:)/;
            }

            result = self.split(pattern);
            /* with "unlimited", ruby leaves a trail on blanks. */
            if (limit !== undefined && limit < 0 && blank_pattern) {
              result.push('');
            }

            prev_index = undefined;
            break;
          }

          if (limit !== undefined && limit > 1 && result.length + 1 == limit) {
            break;
          }
        }

        if (prev_index !== undefined) {
          result.push(self.slice(prev_index, self.length));
        }
      }
    }
    else {
      var splitted = 0, start = 0, lim = 0;

      if (pattern === nil || pattern === undefined) {
        pattern = ' '
      } else {
        pattern = #{Opal.try_convert(pattern, String, :to_str).to_s};
      }

      var string = (pattern == ' ') ? self.replace(/[\r\n\t\v]\s+/g, ' ')
                                    : self;
      var cursor = -1;
      while ((cursor = string.indexOf(pattern, start)) > -1 && cursor < string.length) {
        if (splitted + 1 === limit) {
          break;
        }

        if (pattern == ' ' && cursor == start) {
          start = cursor + 1;
          continue;
        }

        result.push(string.substr(start, pattern.length ? cursor - start : 1));
        splitted++;

        start = cursor + (pattern.length ? pattern.length : 1);
      }

      if (string.length > 0 && (limit < 0 || string.length > start)) {
        if (string.length == start) {
          result.push('');
        }
        else {
          result.push(string.substr(start, string.length));
        }
      }
    }

    if (limit === undefined || limit === 0) {
      while (result[result.length-1] === '') {
        result.length = result.length - 1;
      }
    }

    if (limit > 0) {
      var tail = result.slice(limit - 1).join('');
      result.splice(limit - 1, result.length - 1, tail);
    }

    return result;
  }
end

#squeeze(*sets) ⇒ Object



725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
# File 'opal/opal/corelib/string.rb', line 725

def squeeze(*sets)
  %x{
    if (sets.length === 0) {
      return self.replace(/(.)\1+/g, '$1');
    }
  }

  %x{
    var set = #{Opal.coerce_to(`sets[0]`, String, :to_str).chars};

    for (var i = 1, length = sets.length; i < length; i++) {
      set = #{`set` & Opal.coerce_to(`sets[i]`, String, :to_str).chars};
    }

    if (set.length === 0) {
      return self;
    }

    return self.replace(new RegExp("([" + #{Regexp.escape(`set`.join)} + "])\\1+", "g"), "$1");
  }
end

#start_with?(*prefixes) ⇒ Boolean

Returns:



747
748
749
750
751
752
753
754
755
756
757
758
759
# File 'opal/opal/corelib/string.rb', line 747

def start_with?(*prefixes)
  %x{
    for (var i = 0, length = prefixes.length; i < length; i++) {
      var prefix = #{Opal.coerce_to(`prefixes[i]`, String, :to_str).to_s};

      if (self.indexOf(prefix) === 0) {
        return true;
      }
    }

    return false;
  }
end

#stripObject



761
762
763
# File 'opal/opal/corelib/string.rb', line 761

def strip
  `self.replace(/^\s*/, '').replace(/\s*$/, '')`
end

#sub(pattern, replace = undefined, &block) ⇒ Object



765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
# File 'opal/opal/corelib/string.rb', line 765

def sub(pattern, replace = undefined, &block)
  %x{
    if (typeof(replace) === 'string') {
      // convert Ruby back reference to JavaScript back reference
      replace = replace.replace(/\\([1-9])/g, '$$$1')
      return self.replace(pattern, replace);
    }
    if (block !== nil) {
      return self.replace(pattern, function() {
        // FIXME: this should be a formal MatchData object with all the goodies
        var match_data = []
        for (var i = 0, len = arguments.length; i < len; i++) {
          var arg = arguments[i];
          if (arg == undefined) {
            match_data.push(nil);
          }
          else {
            match_data.push(arg);
          }
        }

        var str = match_data.pop();
        var offset = match_data.pop();
        var match_len = match_data.length;

        // $1, $2, $3 not being parsed correctly in Ruby code
        //for (var i = 1; i < match_len; i++) {
        //  __gvars[String(i)] = match_data[i];
        //}
        #{$& = `match_data[0]`};
        #{$~ = `match_data`};
        return block(match_data[0]);
      });
    }
    else if (replace !== undefined) {
      if (#{replace.is_a?(Hash)}) {
        return self.replace(pattern, function(str) {
          var value = #{replace[str]};

          return (value == null) ? nil : #{value.to_s};
        });
      }
      else {
        replace = #{String.try_convert(replace)};

        if (replace == null) {
          #{raise TypeError, "can't convert #{replace.class} into String"};
        }

        return self.replace(pattern, replace);
      }
    }
    else {
      // convert Ruby back reference to JavaScript back reference
      replace = replace.toString().replace(/\\([1-9])/g, '$$$1')
      return self.replace(pattern, replace);
    }
  }
end

#sum(n = 16) ⇒ Object



827
828
829
830
831
832
833
834
835
836
837
# File 'opal/opal/corelib/string.rb', line 827

def sum(n = 16)
  %x{
    var result = 0;

    for (var i = 0, length = self.length; i < length; i++) {
      result += (self.charCodeAt(i) % ((1 << n) - 1));
    }

    return result;
  }
end

#swapcaseObject



839
840
841
842
843
844
845
846
847
848
849
850
851
# File 'opal/opal/corelib/string.rb', line 839

def swapcase
  %x{
    var str = self.replace(/([a-z]+)|([A-Z]+)/g, function($0,$1,$2) {
      return $1 ? $0.toUpperCase() : $0.toLowerCase();
    });

    if (self.constructor === String) {
      return str;
    }

    return #{self.class.new `str`};
  }
end

#to_fObject



853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
# File 'opal/opal/corelib/string.rb', line 853

def to_f
  %x{
    if (self.charAt(0) === '_') {
      return 0;
    }

    var result = parseFloat(self.replace(/_/g, ''));

    if (isNaN(result) || result == Infinity || result == -Infinity) {
      return 0;
    }
    else {
      return result;
    }
  }
end

#to_i(base = 10) ⇒ Object



870
871
872
873
874
875
876
877
878
879
880
# File 'opal/opal/corelib/string.rb', line 870

def to_i(base = 10)
  %x{
    var result = parseInt(self, base);

    if (isNaN(result)) {
      return 0;
    }

    return result;
  }
end

#to_procObject



882
883
884
885
886
# File 'opal/opal/corelib/string.rb', line 882

def to_proc
  proc do |recv, *args|
    recv.send(self, *args)
  end
end

#to_sObject Also known as: to_str



888
889
890
# File 'opal/opal/corelib/string.rb', line 888

def to_s
  `self.toString()`
end

#tr(from, to) ⇒ Object



896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
# File 'opal/opal/corelib/string.rb', line 896

def tr(from, to)
  %x{
    if (from.length == 0 || from === to) {
      return self;
    }

    var subs = {};
    var from_chars = from.split('');
    var from_length = from_chars.length;
    var to_chars = to.split('');
    var to_length = to_chars.length;

    var inverse = false;
    var global_sub = null;
    if (from_chars[0] === '^') {
      inverse = true;
      from_chars.shift();
      global_sub = to_chars[to_length - 1]
      from_length -= 1;
    }

    var from_chars_expanded = [];
    var last_from = null;
    var in_range = false;
    for (var i = 0; i < from_length; i++) {
      var ch = from_chars[i];
      if (last_from == null) {
        last_from = ch;
        from_chars_expanded.push(ch);
      }
      else if (ch === '-') {
        if (last_from === '-') {
          from_chars_expanded.push('-');
          from_chars_expanded.push('-');
        }
        else if (i == from_length - 1) {
          from_chars_expanded.push('-');
        }
        else {
          in_range = true;
        }
      }
      else if (in_range) {
        var start = last_from.charCodeAt(0) + 1;
        var end = ch.charCodeAt(0);
        for (var c = start; c < end; c++) {
          from_chars_expanded.push(String.fromCharCode(c));
        }
        from_chars_expanded.push(ch);
        in_range = null;
        last_from = null;
      }
      else {
        from_chars_expanded.push(ch);
      }
    }

    from_chars = from_chars_expanded;
    from_length = from_chars.length;

    if (inverse) {
      for (var i = 0; i < from_length; i++) {
        subs[from_chars[i]] = true;
      }
    }
    else {
      if (to_length > 0) {
        var to_chars_expanded = [];
        var last_to = null;
        var in_range = false;
        for (var i = 0; i < to_length; i++) {
          var ch = to_chars[i];
          if (last_from == null) {
            last_from = ch;
            to_chars_expanded.push(ch);
          }
          else if (ch === '-') {
            if (last_to === '-') {
              to_chars_expanded.push('-');
              to_chars_expanded.push('-');
            }
            else if (i == to_length - 1) {
              to_chars_expanded.push('-');
            }
            else {
              in_range = true;
            }
          }
          else if (in_range) {
            var start = last_from.charCodeAt(0) + 1;
            var end = ch.charCodeAt(0);
            for (var c = start; c < end; c++) {
              to_chars_expanded.push(String.fromCharCode(c));
            }
            to_chars_expanded.push(ch);
            in_range = null;
            last_from = null;
          }
          else {
            to_chars_expanded.push(ch);
          }
        }

        to_chars = to_chars_expanded;
        to_length = to_chars.length;
      }

      var length_diff = from_length - to_length;
      if (length_diff > 0) {
        var pad_char = (to_length > 0 ? to_chars[to_length - 1] : '');
        for (var i = 0; i < length_diff; i++) {
          to_chars.push(pad_char);
        }
      }

      for (var i = 0; i < from_length; i++) {
        subs[from_chars[i]] = to_chars[i];
      }
    }

    var new_str = ''
    for (var i = 0, length = self.length; i < length; i++) {
      var ch = self.charAt(i);
      var sub = subs[ch];
      if (inverse) {
        new_str += (sub == null ? global_sub : ch);
      }
      else {
        new_str += (sub != null ? sub : ch);
      }
    }
    return new_str;
  }
end

#tr_s(from, to) ⇒ Object



1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
# File 'opal/opal/corelib/string.rb', line 1031

def tr_s(from, to)
  %x{
    if (from.length == 0) {
      return self;
    }

    var subs = {};
    var from_chars = from.split('');
    var from_length = from_chars.length;
    var to_chars = to.split('');
    var to_length = to_chars.length;

    var inverse = false;
    var global_sub = null;
    if (from_chars[0] === '^') {
      inverse = true;
      from_chars.shift();
      global_sub = to_chars[to_length - 1]
      from_length -= 1;
    }

    var from_chars_expanded = [];
    var last_from = null;
    var in_range = false;
    for (var i = 0; i < from_length; i++) {
      var ch = from_chars[i];
      if (last_from == null) {
        last_from = ch;
        from_chars_expanded.push(ch);
      }
      else if (ch === '-') {
        if (last_from === '-') {
          from_chars_expanded.push('-');
          from_chars_expanded.push('-');
        }
        else if (i == from_length - 1) {
          from_chars_expanded.push('-');
        }
        else {
          in_range = true;
        }
      }
      else if (in_range) {
        var start = last_from.charCodeAt(0) + 1;
        var end = ch.charCodeAt(0);
        for (var c = start; c < end; c++) {
          from_chars_expanded.push(String.fromCharCode(c));
        }
        from_chars_expanded.push(ch);
        in_range = null;
        last_from = null;
      }
      else {
        from_chars_expanded.push(ch);
      }
    }

    from_chars = from_chars_expanded;
    from_length = from_chars.length;

    if (inverse) {
      for (var i = 0; i < from_length; i++) {
        subs[from_chars[i]] = true;
      }
    }
    else {
      if (to_length > 0) {
        var to_chars_expanded = [];
        var last_to = null;
        var in_range = false;
        for (var i = 0; i < to_length; i++) {
          var ch = to_chars[i];
          if (last_from == null) {
            last_from = ch;
            to_chars_expanded.push(ch);
          }
          else if (ch === '-') {
            if (last_to === '-') {
              to_chars_expanded.push('-');
              to_chars_expanded.push('-');
            }
            else if (i == to_length - 1) {
              to_chars_expanded.push('-');
            }
            else {
              in_range = true;
            }
          }
          else if (in_range) {
            var start = last_from.charCodeAt(0) + 1;
            var end = ch.charCodeAt(0);
            for (var c = start; c < end; c++) {
              to_chars_expanded.push(String.fromCharCode(c));
            }
            to_chars_expanded.push(ch);
            in_range = null;
            last_from = null;
          }
          else {
            to_chars_expanded.push(ch);
          }
        }

        to_chars = to_chars_expanded;
        to_length = to_chars.length;
      }

      var length_diff = from_length - to_length;
      if (length_diff > 0) {
        var pad_char = (to_length > 0 ? to_chars[to_length - 1] : '');
        for (var i = 0; i < length_diff; i++) {
          to_chars.push(pad_char);
        }
      }

      for (var i = 0; i < from_length; i++) {
        subs[from_chars[i]] = to_chars[i];
      }
    }
    var new_str = ''
    var last_substitute = null
    for (var i = 0, length = self.length; i < length; i++) {
      var ch = self.charAt(i);
      var sub = subs[ch]
      if (inverse) {
        if (sub == null) {
          if (last_substitute == null) {
            new_str += global_sub;
            last_substitute = true;
          }
        }
        else {
          new_str += ch;
          last_substitute = null;
        }
      }
      else {
        if (sub != null) {
          if (last_substitute == null || last_substitute !== sub) {
            new_str += sub;
            last_substitute = sub;
          }
        }
        else {
          new_str += ch;
          last_substitute = null;
        }
      }
    }
    return new_str;
  }
end

#upcaseObject



1184
1185
1186
# File 'opal/opal/corelib/string.rb', line 1184

def upcase
  `self.toUpperCase()`
end