Capitalize all letters before number in string - javascript

I need to capitalize all letters in the beginning of a string, all letters before the first number that appears in the string.
abc123 will be ABC123
abc123def will be ABC123def
First I find the index of the first number in the string:
var index = myString.search(/\d/);
Then I have a for loop where I try to change every letter before that number:
for (var i=0; i<index; i++) {
myString = myString.charAt(i).toUpperCase() + myString.slice(i+1);
}
The problem is that the code removes the letter in the beginning in every loop.
How can I do it better?
Thank you for your help

You can do it by the code below:
var str = "abc23mlk";
var index = str.search(/\d/);
if (index !== -1) {
str = str.slice(0, index).toUpperCase() + str.slice(index);
}
console.log(str);

You can use a regex and a replacer function:
function replace(text) {
return text.replace(/[a-z]+(?=\d)/i, function(match) {
return match.toUpperCase();
});
}
["abc123", "abc123def", "abcd12efgh34ijkl"].forEach(function(test) {
console.log("'" + test + "' becomes '" + replace(test) + "'");
});
The regex /[a-z]+(?=\d)/i looks for the first sequence of letters ([a-z]+) that is immediately followed by a digit ((?=\d) here as a positive look-ahead so it is not matched).

You also do something like
Find the index as how you are doing now
Substring and capitalize
Slice and append
var myString = "abc123"
var index = myString.search(/\d/);
myString = myString.substr(0,index).toUpperCase() + myString.slice(index);

Related

regex (only 1 dot)

I have a regEx where I replace everything whats not a number:
this.value.replace(/[^0-9\.]/g,'');
how can i make sure it will only allow 1 dot
(the second dot will be replaced like the others)
(I know you can use input just number (thats not an option in this project for me))
You can use a simple trick of:
splitting a string by ., and then only joining the first two elements of the array (using .splice(0,2)) with a . and the rest with nothing
using a simple regex pattern to replace all non-digit and non-period characters: /[^\d\.]/gi
Here is an example code:
// Assuming that `yourString` is the input you want to parse
// Step 1: Split and rejoin, keeping only first occurence of `.`
var splitStr = yourString.split('.');
var parsedStr = splitStr[0];
if (splitStr.length) {
parsedStr = splitStr.splice(0, 2).join('.') + splitStr.join('');
}
// Step 2: Remove all non-numeric characters
parsedStr = parsedStr.replace(/[^\d\.]/gi, '');
Proof-of-concept example:
var tests = [
'xx99',
'99xx',
'xx99xx',
'xxxx999.99.9xxx',
'xxxx 999.99.9 xxx',
'xx99xx.xx99xx.x9',
'xx99xx.99x.9x',
'xx99.xx99.9xx'
];
for (var i = 0; i < tests.length; i++) {
var str = tests[i];
// Split and rejoin, keeping only first occurence of `.`
var splitStr = str.split('.');
var parsedStr = splitStr[0];
if (splitStr.length) {
parsedStr = splitStr.splice(0, 2).join('.') + splitStr.join('');
}
// Remove all non-numeric characters
parsedStr = parsedStr.replace(/[^\d\.]/gi, '');
console.log('Original: ' + str + '\nParsed: ' + parsedStr);
}
I resolved it with.
this.value = this.value.replace(/.*?(\d+.\d+).*/g, "$1");

I don't get this task in Java Script

Please help me. I'm doing exercise and I don't understand what I'm doing wrong if all conditions execute. The task consists in returning the provided string with only the first letter of each word capitalized. My code performs this condition, but It doesn't get me ahead.
function titleCase(str) {
var text = str.toLowerCase();
var arr = text.split(" ");
var txt = " ";
var i;
for(i=0; i < arr.length; i++) {
txt += arr[i][0].toUpperCase() + arr[i].slice(1) + " " ;
}
return txt;
}
titleCase("sHoRt AnD sToUt");
You are adding extra whitespace (var txt = " " should be var text = ''), try this instead:
function titleCase(str) {
var text = str.toLowerCase();
// split on spaces, map over array and return capitalized word and join on space
return text.split(' ').map((word) => {
return word[0].toUpperCase() + word.slice(1);
}).join(' ');
}
alert(titleCase("sHoRt AnD sToUt"));
If your goal is to return the string back with the first letters capitalized, I can see one problem in your output. You should be returning
"Short And Stout"
but instead you return
" Short And Stout "
with a space before and after your string. You can fix this by initializing txt to an empty string rather than a space, and then either trimming the last space off at the end after your loop, or by only adding the space if you aren't on the last element of arr. That is:
var txt = "";
for(var i=0; i < arr.length; i++) {
txt += arr[i][0].toUpperCase() + arr[i].slice(1);
if (i != arr.length - 1) txt += " ";
}
You can use regular expression instead.
function titleCase(txt){
return txt.toLowerCase().replace(/\b\w/g, function(m){return m.toUpperCase();});
}
console.log(titleCase("sHoRt AnD sToUt"));//"Short And Stout"
Some explanation.
// regular expression (RegEx), g for global (else first only)
\b word boundary
\w any word symbol a-z (plus _)
m (function parameter) is match in the string

Regex to remove all characters that are repeated

I'm looking for a regex that will remove all characters that have been repeated in a string. I already solved this using a loop. Just wondering if there is a regex that can do the same.
this is what i have so far:
function onlyUnique(str) {
var re = /(.)(?=.*\1)/g
return str.replace(re, '');
}
This string:
"rc iauauc!gcusa_usdiscgaesracg"
should end up as this:
" !_de"
You can use Array#filter with Array#indexOf and Array#lastIndexOf to check if the element is repeated.
var str = "rc iauauc!gcusa_usdiscgaesracg";
// Split to get array
var arr = str.split('');
// Filter splitted array
str = arr.filter(function (e) {
// If index and lastIndex are equal, the element is not repeated
return arr.indexOf(e) === arr.lastIndexOf(e);
}).join(''); // Join to get string from array
console.log(str);
document.write(str);
well, no idea if regex can do that, but you could work it out using for loop, like:
function unikChars(str) {
store = [];
for (var a = 0, len = str.length; a < len; a++) {
var ch = str.charAt(a);
if (str.indexOf(ch) == a && str.indexOf(ch, a + 1) == -1) {
store.push(ch);
}
}
return store.join("");
}
var str = 'rc iauauc!gcusa_usdiscgaesracg';
console.log(unikChars(str)); //gives !_de
Demo:: jsFiddle
Your regex searches pairs of duplicated characters and only removes the first one. Therefore, the latest duplicate won't be removed.
To address this problem, you should remove all duplicates simultaneously, but I don't think you can do this with a single replace.
Instead, I would build a map which counts the occurrences of each character, and then iterate the string again, pushing the characters that appeared only once to a new string:
function onlyUnique(str) {
var map = Object.create(null);
for(var i=0; i<str.length; ++i)
map[str[i]] = (map[str[i]] || 0) + 1;
var chars = [];
for(var i=0; i<str.length; ++i)
if(map[str[i]] === 1)
chars.push(str[i]);
return chars.join('');
}
Unlike indexOf, searches in the hash map are constant on average. So the cost of a call with a string of n characters will be n.
If you want to do it with a regex, you can use your own regex with a callback function inside a replace.
var re = /(.)(?=.*\1)/g;
var str = 'rc iauauc!gcusa_usdiscgaesracg';
var result = str;
str.replace(re, function(m, g1) {
result = result.replace(RegExp(g1.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g"), '');
});
document.getElementById("r").innerHTML = "'" + result + "'";
<div id="r"/>
The idea is: get the duplicated character, and remove it from the input string. Note that escaping is necessary if the character might be a special regex metacharacter (thus, g1.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") is used).
Another idea belongs to Washington Guedes in his deleted answer, I just add my own implementation here (with removing duplicate symbols from the character class and escaping special regex chars):
var s = "rc iauauc!gcusa_u]sdiscgaesracg]";
var delimiters= '[' + s.match(/(.)(?=.*\1)/g).filter(function(value, index, self) { // find all repeating chars
return self.indexOf(value) === index; // get unique values only
}).join('').replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + ']'; // escape special chars
var regex = new RegExp(delimiters, 'g'); // build the global regex from the delimiters
var result = s.replace(regex, ''); // obtain the result
document.getElementById("r2").innerHTML = "'" + result + "'";
<div id="r2"/>
NOTE: if you want to support newline symbols as well, replace . with [^] or [\s\S] inside the regex pattern.
function onlyUnique(str) {
// match the characters you want to remove
var match = str.match(/(.)(?=.*\1)/g);
if (match) {
// build your regex pattern
match = '[' + match.join('') + ']';
}
// if string is already unique return the string
else {
return str
}
// create a regex with the characters you want to remove
var re = new RegExp(match, 'g');
return str.replace(re, '');
}

Replacing multiple characters in a string with a string rewrites characters

I have a variable (in this example var str = "I!%1$s-I!%2$s TTL!%3$s";), in which I want to replace the % with elements from an array (var regex = ['aaa', 'bbb', 'ccc'];).
I google around a bit and found this solution, but I'm having trouble implementing it. My problem is that I want to replace a single character with multiple characters, and then continue the string, but this just overwrites the characters. I actually have no idea why.
Any help is appreciated, my code below
String.prototype.replaceAt = function(index, character) {
return this.substr(0, index) + character + this.substr(index + character.length);
}
var str = "I!%1$s-I!%2$s TTL!%3$s";
var regex = ['replace', 'replace', 'replace'];
//find position of %
var find = /%/gi,
result, pos = [];
while ((result = find.exec(str))) {
pos.push(result.index);
}
//replace % with regex elements
for (x = 0; x < pos.length; x++) {
str = str.replaceAt(pos[x], regex[x]);
}
document.write(str);
Use replacement function, like this
var str = "I!%1$s-I!%2$s TTL!%3$s";
var regex = ['[123]', '[456]', '[789]'];
console.log(str.replace(/%(\d+)/g, function(match, group1) {
return regex[parseInt(group1) - 1] + group1;
}));
// I![123]1$s-I![456]2$s TTL![789]3$s
The RegEx /%(\d+)/g matches anything of the pattern % followed by one or more digits. And it captures the digits as a group. Then the exact match and the group is passed to the function to get the actual replacement. In the function, you convert the group to a number with parseInt and return the respective value from the regex array.

Javascript Return the location of the first letter of each word in a string using a loop

Having trouble coming up with code doing this.
So for example here is my string.
var str = "Hello how are you today?";
How would I manipulate this string to return the position of the first letter of each word using a loop?
this will give you the result with less complicated code and a single loop
function foo(str) {
var pos = [];
var words = str.split(' ');
pos.push(1);
var prevWordPos;
for (var i = 1; i < words.length; i++) {
prevWordPos = pos[i - 1] + words[i - 1].length;
pos.push((str.indexOf(words[i], prevWordPos) + 1));
}
return pos;
}
You should search for a question before asking it in case it's already been asked and answered.
Get first letter of each word in a string, in Javascript
You can use a regexp replace passing a function instead of a replacement string, this will call the function for each match:
str.replace(/[^ ]+/g, function(match, pos) {
console.log("Word " + match + " starts at position " + pos);
});
The regexp meaning is:
[^ ]: anything excluding space
+: one or more times
"g" option: not only first match, but each of them
in other words the function will be called with sequences of non-spaces. Of course you can define what you consider a "word" differently.
Here is a Solution with two Loops, i hope that is close enough ;)
var starts = [];
var str = "How are you doing today?";
//var count = 0;
var orgStr = str;
while (str.indexOf(" ") > 0) {
if (starts.length > 0) {
starts.push(starts[starts.length - 1] + str.indexOf(" ") +1);
} else {
starts.push(1);
starts.push(str.indexOf(" ") +2);
//alert(str);
}
str = str.substring(str.indexOf(" ") + 1);
}
for (var i = 0; i < starts.length; i++) {
alert(starts[i] + ": " + orgStr.substring(starts[i]-1,starts[i]))
}
Easiest would be to search a regular expression \b\w and collect match.start() match.index for each match. Loop while there's matches.
EDIT: wrong language. lol.

Categories