Transform string in JavaScript
How would you do this...?
I am trying to write a string transformer, which capitalises certain letter in string.
Examples
lorem lipum lampum => lorem Lipum lampum
po开发者_如何学Gopud pidem papusek => popud pidem Papusek
Thanks!
This should randomly capitalize every fifth string:
var s = "lorem lipum lampum";
var a = s.split(" ");
for (var i=0; i < a.length; i++) {
if (Math.random() > 0.2) {
a[i] = a[i].charAt(0).toUpperCase() + a[i].substring(1);
}
}
s = a.join(" ");
Here's an update now that you clarified:
var doIt = function (s, which) {
var a = s.split(" ");
a[which] = a[which].charAt(0).toUpperCase() + a[which].substring(1);
return a.join(" ");
}
Provided you can get the pattern definitively set, use Regex to find the pieces that need capitalizing. If you are using a dictionary, a state machine pattern is the best. For easy coding, the fastest is running through the words one at a time and finding those that fit the pattern. If perf is the main need, there are tricky ways to increase perf, including (at the extreme end) using binary.
精彩评论