I need to have the right function to test, which is giving me string from a fullName and which I have to split and using for loop change the letters to a char "*". I want to keep the first upperCase visible: here is my code:
var fullName = "Jozko Baci";
function testSamoUloha(fullName) {
var splitString=fullName.split("");
for (var i=1;i<splitString[1].length;i++) {
splitString[1].replace(splitString[1][i],"*");
}
var anonymName =splitString[0]+" "+splitString[1];
console.log(anonymName);
}
testSamoUloha();
I'm really new to it, this problem took me two hours to have at least some solution.
I expect that from the string above will become string saved in variable anonymName as "Jozko B***";
You can use the following regex if you'd like to make your code shorter:
(?<=^.+\s\S+)\w
it will match any letter \w that is preceded (?<= by start of string ^, any number of chars .+, a whitespace \s and one or more non-whitespace characters \S+
const fullName = "Jozko Baci";
const censored = fullName.replace(/(?<=^.+\s\S+)\w/g, '*');
console.log(censored);
Strings are immutable (you can't change them) so this code:
splitString[1].replace(splitString[1][i],"*");
won't work in any situation.
What I suggest is you create a temporary string, then loop over the whole of your second word. If the index of the loop is 0 add the letter to the temporary string, otherwise add a *:
var fullName = "Jozko Baci";
function testSamoUloha(fullName) {
var splitString = fullName.split(' ');
// Create a temporary string
var tempString = '';
// Loop over the whole second word
for (var i = 0; i < splitString[1].length; i++) {
// If the index is greater than zero (not the first letter)
// add a * to the temporary string
if (i > 0) {
tempString += '*';
// otherwise, if the index is 0, add the letter
// to the temporary string instead
} else {
tempString += splitString[1][i];
}
}
// Return your string from your function
return splitString[0] + ' ' + tempString;
}
// Make sure you pass in the fullName as an argument
console.log(testSamoUloha(fullName));
The above code looks fine, just added a fix in this line
splitString[1].replace(splitString[1][i],"*")
Also added fix to var splitString=fullName.split(" ");
replaced
fullName.split(""); // ['J', 'o', 'z', 'k', 'o', ' ', 'B', 'a', 'c', 'i']
with
fullName.split(" "); // ['Jozko', 'Baci']
if you use replace on a string it returns the new string after replace
, its is not rewriting the existing string
for eg:
var a = "hello";
a.replace('o', '*') // returns hell*
a // has hello
but if you do
a = a.replace('o', '*') // returns hell* and rewrites a
a // hell*
similarly after adding this fix the existing code works fine
var fullName = "Jozko Baci";
function testSamoUloha(fullName) {
var splitString=fullName.split(" ");
for (var i=1;i<splitString[1].length;i++) {
splitString[1] = splitString[1].replace(splitString[1][i],"*");
}
var anonymName =splitString[0]+" "+splitString[1];
console.log(anonymName);
}
testSamoUloha(fullName);
Could do it with something like this;
const fullName = "Jozko Baci";
// Break name into words (firstName, lastName)
let res = fullName.split(' ').map((word, wordIndex) =>
// If after firstName
wordIndex > 0
// Hide all but first character in word
? word.split('').map((char, charIndex) => (charIndex > 0 ? '*' : char)).join('')
// Else, show entire word
: word
).join(' '); // Join words back together (firstName, lastName)
console.log(res);
Hope this helps,
Related
I'm trying to do a challenge which is converting all strings into camelCase but without using regex, only using the methods like(split, slice, replace, includes.. etc). Some words have spaces and should remove them. Here's the CODE and I'm really STUCK. NOTE: the user enters the STRING and when user clicks the button should return to the camelCase.
INPUT =>
//underscore_case
//first_name
//Some_Variable
// calculate_AGE
//delayed_departure
OUTPUT =>
//underscoreCase
//firstName
//someVariable
//calculateAge
//delayedDeparture
document.body.append(document.createElement('textarea'));
document.body.append(document.createElement('button'));
document.querySelector('button').addEventListener('click', function() {
const text = document.querySelector('textarea').value;
const row = text.split('\n');
let [...n] = '';
for (const theText of row) {
const lowerText = theText.toLowerCase().trim();
if (lowerText.includes('_')) {
n = lowerText.replace('_', ' ');
console.log([...n]);
}
}
});
Explanation of this simple algorithm:
Your input must have words that split by a certain character, as you need something to identify which part of the string is a word. Let's assume your string has words separated by '//' instead of spaces as you mentioned in the comments, and each of those words is split by '_'.
First you need to split all words in the string into an array, you can use the split() method in order to do that.
Then when iterating through each word, split it again with split() but this time with whatever identifies the different words, in our case it's _.
Iterate through each split words, if it's the first word lowercase it using toLowerCase() and add it to the new word variable, if not, lowercase it and capitalize the first letter.
And that's it. Here's the implementation:
const inputWithoutCamelCase = 'hello_world // HOW_ARE_YOU // foo_BAR'
function stringToCamelCase(string) {
const allNames = string.split('//')
let camelCasedString = '';
for (const name of allNames) {
camelCasedString += nameToCamelCaseHelper(name);
}
return camelCasedString;
}
function nameToCamelCaseHelper(word) {
const splittedName = word.split('_');
let camelCasedName = '';
for (let i = 0; i < splittedName.length; i++) {
if (i === 0) {
camelCasedName += splittedName[i].toLowerCase();
} else {
camelCasedName += capitalizeFirstLetter(splittedName[i].toLowerCase())
}
}
return camelCasedName;
}
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
stringToCamelCase(inputWithoutCamelCase) // helloWorld howAreYou fooBar
I need to have no more than 25 characters in each word. Yes, I could use break-word:break-all, however, I don't like how it all works against long words.
I wrote a JavaScript function that truncates these words by letter and adds a separator. Could you suggest a better option or rewrite this program in php, since I don't know php very well yet
if(document.getElementById('title_parent') && document.getElementById('title')) {
document.getElementById('title').oninput = function() {
const parent = document.getElementsByClassName('edit-project-title')[0];
parent.innerHTML = this.value ? truncate(this.value,20,'...') : " ";
}
}
function truncate(str,maxWordLength,endLetters) {
if ("string" !== typeof str) {
return '';
}
const words = str.split(/\s+/g);
const completedWords = [];
for (let word of words) {
if (word.length > maxWordLength)
completedWords.push(word.slice(0,maxWordLength+1) + endLetters);
else
completedWords.push(word);
}
return completedWords.join(' ').replace(/\</g, "<");
}
Try this for a PHP rewrite of your JavaScript function. See comments for step-by-step explanation.
Outputs: here are some short words and a <really long one> now: pneumonoultramicrosco...
<?php
// Set some default values for max word length and end letters arguments.
// If you pass these, your paremeter values will be used.
function truncate(string $input, int $maxWordLength = 20, string $endLetters = '...')
{
// No manual type checking required if you use declare(strict_types=1),
// in combination with type hinting in the argument list.
// foreach() replaces for ... of
// preg_split() replaces String.prototype.split()
foreach (preg_split('/\s+/', $input) as $word)
{
// strlen() replaces .length
if (strlen($word) > $maxWordLength)
// substr() replaces String.prototype.slice()
$completedWords[] = substr($word, 0, $maxWordLength + 1) . $endLetters;
else
$completedWords[] = $word;
}
// implode() replaces .join()
// str_replace() replaces .replace()
return str_replace('<', '<', implode(' ', $completedWords));
}
$input = 'here are some short words and a <really long one> now: pneumonoultramicroscopicsilicovolcanoconiosis';
echo truncate($input);
I am trying to find number of occurrences of a string letter(variable) in a string word, using a regex constructor but it doesn't work.
function getNumberOfOccurrences()
{
//get input from user:
var inputWord = document.getElementById("wordInputField").value;
inputWord = inputWord+""; // turn it into a string
var inputLetter = document.getElementById("letterInputField").value;
inputLetter = inputLetter+""; // turn it into a string
if(checkInput(inputWord , inputLetter)) // other function that checks the input
{
var rgxInputLetter = new RegExp(inputLetter, "g"); //use regex constructor for the match function:
var resultArray = inputWord.match(rgxInputLetter); // use match to find occurrences. match returns an array
var occurences = resultArray.length; // length of array should be the occurrences
if(isNaN(occurences) && occurences >= 0) // check that match function worked and an array was returned
{
document.getElementById("resultField").innerHTML = "There are "+occurences + " occurrences of: \""+inputLetter+"\" in the word: \""+inputWord+"\"";
}
else
{
document.getElementById("resultField").innerHTML = "There are no occurrences of: \""+inputLetter+"\" in the word: \""+inputWord+"\"";
}
}
}
It always gives me an error that the resultArray is null.
even if I write inputLetter = "a" or inputWord = "something" just before the match function.
Why it doesn't work?
Found that it actually works , and the problem was the last if condition isNaN(occurences).
The condition as it is checks that occurences is not a number.
Should have added a ! sign. -_-
so this fixed it:
if( ! isNaN(occurences) && occurences >= 0)
I'm aware of the CSS attribute text-transform: capitalize but can anyone help me with replicating this using Javascript?
I would like to pass an argument to my function which will return the string with the first letter of each word capitalized.
I've got this far but I'm stuck trying to break my array of strings in to chunks:
function upper(x){
x = x.split(" ");
// this function should return chunks but when called I'm getting undefined
Array.prototype.chunk = function ( n ) {
return [ this.slice( 0, n ) ].concat( this.slice(n).chunk(n) );
};
x = x.chunk;
}
upper("chimpanzees like cigars")
after the chunk I'm guessing I need to again split each chunk in to the first character and the remaining characters, use .toUpperCase() on the first character, join it back up with the remaining and then join up the chunks again in to a string?
Is there a simpler method for doing this?
I came up with a solution for both a single word and also for an array of words. It will also ensure that all other letters are lowercase for good measure. I used the Airbnb style guide as well. I hope this helps!
const mixedArr = ['foo', 'bAr', 'Bas', 'toTESmaGoaTs'];
const word = 'taMpa';
function capitalizeOne(str) {
return str.charAt(0).toUpperCase().concat(str.slice(1).toLowerCase());
}
function capitalizeMany(args) {
return args.map(e => {
return e.charAt(0).toUpperCase().concat(e.slice(1).toLowerCase());
});
};
const cappedSingle = capitalizeOne(word);
const cappedMany = capitalizeMany(mixedArr);
console.log(cappedSingle);
console.log(cappedMany);
The map function is perfect for this.
w[0].toUpperCase() : Use this to capitalize the first letter of each word
w.slice(1): Return the string from the second character on
EDGE Case
If the user doesn't enter a string, the map function will not work and an error will be raised. This can be guarded against by checking if the user actually entered something.
var userInput = prompt("Enter a string");
var capitalizedString = userInput == "" ? "Invalid String" :
userInput.split(/\s+/).map(w => w[0].toUpperCase() + w.slice(1)).join(' ');
console.log(capitalizedString);
You can use the following solution which doesn't use regex.
function capitalize(str=''){
return str.trim().split('')
.map((char,i) => i === 0 ? char.toUpperCase() : char )
.reduce((final,char)=> final += char, '' )
}
capitalize(' hello') // Hello
"abcd efg ijk lmn".replace(/\b(.)/g, (m => m.toUpperCase())) // Abcd Efg Ijk Lmn
You may want to try a regex approach:
function upperCaseFirst(value) {
var regex = /(\b[a-z](?!\s))/g;
return value ? value.replace(regex, function (v) {
return v.toUpperCase();
}) : '';
}
This will grab the first letter of every word on a sentence and capitalize it, but if you only want the first letter of the sentence, you can just remove the g modifier at the end of the regex declaration.
or you could just iterate the string and do the job:
function capitalize(lowerStr){
var result = "";
var isSpacePrevious = false;
for (var i=0; i<lowerStr.length; i++){
if (i== 0 || isSpacePrevious){
result += lowerStr[i].toUpperCase();
isSpacePrevious = false;
continue;
}
if (lowerStr[i] === ' '){
isSpacePrevious = true;
}
result += lowerStr[i];
}
return result;
}
I have the following code as part of a table sorting script. As it is now, it allows names in the "FIRST LAST" format to be sorted on LAST name by "reformatting" to "LAST, FIRST".
var FullName = fdTableSort.sortText;
function FullNamePrepareData(td, innerText) {
var a = td.getElementsByTagName('A')[0].innerHTML;
var s = innerText.split(' ');
var r = '';
for (var i = s.length; i > 0; i--) {
r += s[i - 1] + ', ';
}
return r;
}
It currently seems to sort on the name after the LAST space (ex. Jean-Claude Van Damme would sort on 'D').
How could I change this script to sort on the FIRST space (so Van Damme shows up in the V's)?
Thanks in advance!
Instead of the .split() and the loop you could do a replace:
return innerText.replace(/^([^\s]+)\s(.+)$/,"$2, $1");
That is, find all the characters up to the first space with ([^\s]+) and swap it with the characters after the first space (.+), inserting a comma at the same time.
You can shorten that functio a bit by the use of array methods:
function FullNamePrepareData(td, innerText) {
return innerText.split(' ').reverse().join(', ');
}
To put only the first name behind everything else, you might use
function FullNamePrepareData(td, innerText) {
var names = innerText.split(' '),
first = names.shift();
return names.join(' ')+', '+first;
}
or use a Regexp replace:
function FullNamePrepareData(td, innerText) {
return innerText.replace(/^(\S+)\s+([\S\s]+)/, "$2, $1");
}
I don't know where the sorting happens; it sounds like you just want to change the reordering output.
The simplest would be to use a regexp:
// a part without spaces, a space, and the rest
var regexp = /^([^ ]+) (.*)$/;
// swap and insert a comma
"Jean-Claude Van Damme".replace(regexp, "$2, $1"); // "Van Damme, Jean-Claude"
I think you're after this:
var words = innerText.split(' '),
firstName = words.shift(),
lastName = words.join(' ');
return lastName + ', ' + firstName;
Which would give you "Van Damme, Jean-Claude"