function dashes(str) {
str = str.replace(/_/g,' ').replace(/\s+/g,"-").toLowerCase();
return str;
}
//test cases
dashes("thisCakeIsDelicious");
dashes("TheBig cat was Boastful");
the desired output respectively are: "this-cake-is-delicious" and "the-big-cat-was-boastful".
How do i put a space between "TheBig" without contradicting the space before "Boastful". I have tried regex particular capital letters but as you can see Big and Boastful start with B.
This should work, but I'm not absolutely sure about the requirements so I decided to divide by word not by letter (so LLLLie will result in llllie, not l-l-l-lie)
([a-z]+)([A-Z]{1})|(\s)
Matches:
([a-z]+): 1 or more lowercase letter
([A-Z]{1}): 1 uppercase letter
(\s+): one or more whitespace character (equal to [\r\n\t\f\v ])
var dasher = function(str) {
return str
.trim()
.replace(/([a-z]+)([A-Z]{1})|(\s+)/g, '$1-$2')
.toLowerCase();
}
console.log(dasher('thisCakeIsDelicious'));
console.log(dasher('TheBig cat was Boastful'));
console.log(dasher('The cakeIsA LLLLLie'));
console.log(dasher(' JeremySpoke inClass Today'));
x = "thisCakeIsDelicious";
x.replace(/([a-z](?=[A-Z]))| /g, '$1-');
results in
this-Cake-Is-Delicious,
and
x = "TheBig cat was Boastful";
x.replace(/([a-z](?=[A-Z]))| /g, '$1-');
results in
The-Big-cat-was-Boastful
You could use a callback in the replace function
function dashes(str) {
return str.replace(/(?!^)(\s?[A-Z\s+])/g, function(x) {
return '-' + x.trim();
}).toLowerCase();
}
//test cases
console.log( dashes("thisCakeIsDelicious") );
console.log( dashes("TheBig cat was Boastful") );
Related
I have to replace all letters of name on ****.
Example:
Jeniffer -> J****r
I try $(this).text( $(this).text().replace(/([^\w])\//g, "*"))
Also, if name is Ron -> R****n
You can use a regular expression for this, by capturing the first and last letters in a capture group and ignoring all letters between them, then using the capture groups in the replacement:
var updated = name.replace(/^(.).*(.)$/, "$1****$2");
Live Example:
function obscure(name) {
return name.replace(/^(.).*(.)$/, "$1****$2");
}
function test(name) {
console.log(name, "=>", obscure(name));
}
test("Ron");
test("Jeniffer");
But it's perhaps easier without:
var updated = name[0] + "****" + name[name.length - 1];
Live Example:
function obscure(name) {
return name[0] + "****" + name[name.length - 1];;
}
function test(name) {
console.log(name, "=>", obscure(name));
}
test("Ron");
test("Jeniffer");
Both of those do assume the names will be at least two characters long. I pity the fool who tries this on Mr. T's surname.
Since, you need to have four asterisk on each condition, you can create a reusable function that will create this format for you:
function replace(str){
var firstChar = str.charAt(0);
var lastChar = str.charAt(str.length-1);
return firstChar + '****' + lastChar;
}
var str = 'Jeniffer';
console.log(replace(str));
str = 'America';
console.log(replace(str))
Appears that you're looking for regex lookaround
Regex: (?<=\w)(\w+)(?=\w) - group 1 matches all characters which follow one character and followed by another one.
Tests: https://regex101.com/r/PPeEqx/2/
More Info: https://www.regular-expressions.info/lookaround.html
Find first and last chars and append **** to the first one and add the last one:
const firstName = 'Jeniffer';
const result = firstName.match(/^.|.$/gi).reduce((s, c, i) => `${s}${!i ? `${c}****` : c }`, '');
console.log(result);
I'm learning how to capitalize the first letter of each word in a string and for this solution I understand everything except the word.substr(1) portion. I see that it's adding the broken string but how does the (1) work?
function toUpper(str) {
return str
.toLowerCase()
.split(' ')
.map(function(word) {
return word[0].toUpperCase() + word.substr(1);
})
.join(' ');
}
console.log(toUpper("hello friend"))
The return value contain 2 parts:
return word[0].toUpperCase() + word.substr(1);
1) word[0].toUpperCase(): It's the first capital letter
2) word.substr(1) the whole remain word except the first letter which has been capitalized. This is document for how substr works.
Refer below result if you want to debug:
function toUpper(str) {
return str
.toLowerCase()
.split(' ')
.map(function(word) {
console.log("First capital letter: "+word[0]);
console.log("remain letters: "+ word.substr(1));
return word[0].toUpperCase() + word.substr(1);
})
.join(' ');
}
console.log(toUpper("hello friend"))
Or you could save a lot of time and use Lodash
Look at
https://lodash.com/docs/4.17.4#startCase -added/edited-
https://lodash.com/docs/4.17.4#capitalize
Ex.
-added/edited-
You may what to use startCase, another function for capitalizing first letter of each word.
_.startCase('foo bar');
// => 'Foo Bar'
and capitalize for only the first letter on the sentence
_.capitalize('FRED');
// => 'Fred'
Lodash is a beautiful js library made to save you a lot of time.
There you will find a lot of time saver functions for strings, numbers, arrays, collections, etc.
Also you can use it on client or server (nodejs) side, use bower or node, cdn or include it manually.
Here is a quick code snippet. This code snippet will allow you to capitalize the first letter of a string using JavaScript.
function capitlizeText(word)
{
return word.charAt(0).toUpperCase() + word.slice(1);
}
The regexp /\b\w/ matches a word boundary followed by a word character. You can use this with the replace() string method to match then replace such characters (without the g (global) regexp flag only the first matching char is replaced):
> 'hello my name is ...'.replace(/\b\w/, (c) => c.toUpperCase());
'Hello my name is ...'
> 'hello my name is ...'.replace(/\b\w/g, (c) => c.toUpperCase());
'Hello My Name Is ...'
function titleCase(str) {
return str.toLowerCase().split(' ').map(x=>x[0].toUpperCase()+x.slice(1)).join(' ');
}
titleCase("I'm a little tea pot");
titleCase("sHoRt AnD sToUt");
The major part of the answers explains to you how works the substr(1). I give to you a better aproach to resolve your problem
function capitalizeFirstLetters(str){
return str.toLowerCase().replace(/^\w|\s\w/g, function (letter) {
return letter.toUpperCase();
})
}
Explanation:
- First convert the entire string to lower case
- Second check the first letter of the entire string and check the first letter that have a space character before and replaces it applying .toUpperCase() method.
Check this example:
function capitalizeFirstLetters(str){
return str.toLowerCase().replace(/^\w|\s\w/g, function (letter) {
return letter.toUpperCase();
})
}
console.log(capitalizeFirstLetters("a lOt of words separated even much spaces "))
Consider an arrow function with an implicit return:
word => `${word.charAt(0).toUpperCase()}${word.slice(1).toLowerCase()}`
This will do it in one line.
Using ES6
let captalizeWord = text => text.toLowerCase().split(' ').map( (i, j) => i.charAt(0).toUpperCase()+i.slice(1)).join(' ')
captalizeWord('cool and cool')
substr is a function that returns (from the linked MDN) a new string containing the extracted section of the given string (starting from the second character in your function). There is a comment on the polyfill implementation as well, which adds Get the substring of a string.
function titlecase(str){
let titlecasesentence = str.split(' ');
titlecasesentence = titlecasesentence.map((word)=>{
const firstletter = word.charAt(0).toUpperCase();
word = firstletter.concat(word.slice(1,word.length));
return word;
});
titlecasesentence = titlecasesentence.join(' ');
return titlecasesentence;
}
titlecase('this is how to capitalize the first letter of a word');
const capitalize = str => {
if (typeof str !== 'string') {
throw new Error('Invalid input: input must of type "string"');
}
return str
.trim()
.replace(/ {1,}/g, ' ')
.toLowerCase()
.split(' ')
.map(word => word[0].toUpperCase() + word.slice(1))
.join(' ');
};
sanitize the input string with trim() to remove whitespace from the leading and trailing ends
replace any extra spaces in the middle with a RegExp
normalize and convert it all toLowerCase() letters
convert the string to an array split on spaces
map that array into an array of capitalized words
join(' ') the array with spaces and return the newly capitalized string
Whole sentence will be capitalize only by one line
"my name is John".split(/ /g).map(val => val[0].toUpperCase() + val.slice(1)).join(' ')
Output "My Name Is John"
A nice simple solution, using pure JavaScript. JSFiddle
function initCap(s) {
var result = '';
if ((typeof (s) === 'undefined') || (s == null)) {
return result;
}
s = s.toLowerCase();
var words = s.split(' ');
for (var i = 0; i < words.length; ++i) {
result += (i > 0 ? ' ' : '') +
words[i].substring(0, 1).toUpperCase() +
words[i].substring(1);
}
return result;
}
Here is an example of how substr works: When you pass in a number, it takes a portion of the string based on the index you provided:
console.log('Testing string'.substr(0)); // Nothing different
console.log('Testing string'.substr(1)); // Starts from index 1 (position 2)
console.log('Testing string'.substr(2));
So, they are taking the first letter of each word, capitalizing it, and then adding on the remaining of the word. Ance since you are only capitalizing the first letter, the index to start from is always 1.
In word.substr(i), the param means the index of the word. This method cuts the word from the letter whose index equals i to the end of the word.
You can also add another param like word.substr(i, len), where len means the length of the character segmentation. For example:
'abcde'.substr(1, 2) → bc.
function toTitleCase(str)
{
return str.replace(/\w\S*/g, function(txt){return
txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}
Just map through if an array set the first letter as uppercase and concatenate with other letters from index 1.
The array isn't your case here.
const capitalizeNames = (arr) => {
arr.map((name) => {
let upper = name[0].toUpperCase() + name.substr(1)
console.log(upper)
})
}
Here's another clean way of Capitalizing sentences/names/... :
const capitalizeNames =(name)=>{
const names = name.split(' ') // ['kouhadi','aboubakr',essaaddik']
const newCapName = [] // declaring an empty array
for (const n of names){
newCapName.push(n.replace(n[0], n[0].toUpperCase()));
}
return newCapName.join(' ')
}
capitalizeNames('kouhadi aboubakr essaaddik'); // 'Kouhadi Aboubakr Essaaddik'
You could use these lines of code:
function toUpper(str) {
return [str.split('')[0].toUpperCase(), str.split('').slice(1, str.split('').length).join("")].join("")
}
Basically it will split all characters, slice it, create a new array without the first entry/character and replace the first entry/character with an uppercase verion of the character.
(Yes, this was tested and it works on Edge, Chrome and newer versions of Internet Explorer.)
This is probably not the greatest answer, but hopefully it works well enough for you.
I know the regex that separates two words as following:
input:
'WonderWorld'
output:
'Wonder World'
"WonderWorld".replace(/([A-Z])/g, ' $1');
Now I am looking to remove number in year format from string, what changes should be done in the above code to get:
input
'WonderWorld 2016'
output
'Wonder World'
You can match the location before an uppercase letter (but excluding the beginning of a line) with \B(?=[A-Z]) and match the trailing spaces if any with 4 digits right before the end (\s*\b\d{4}\b). In a callback, check if the match is not empty, and replace accordingly. If a match is empty, we matched the location before an uppercase letter (=> replace with a space) and if not, we matched the year at the end (=> replace with empty string). The four digit chunks are only matched as whole words due to the \b word boundaries around the \d{4}.
var re = /\B(?=[A-Z])|\s*\d{4}\b/g;
var str = 'WonderWorld 2016';
var result = str.replace(re, function(match) {
return match ? "" : " ";
});
document.body.innerHTML = "<pre>'" + result + "'</pre>";
A similar approach, just a different pattern for matching glued words (might turn out more reliable):
var re = /([a-z])(?=[A-Z])|\s*\b\d{4}\b/g;
var str = 'WonderWorld 2016';
var result = str.replace(re, function(match, group1) {
return group1 ? group1 + " " : "";
});
document.body.innerHTML = "<pre>'" + result + "'</pre>";
Here, ([a-z])(?=[A-Z]) matches and captures into Group 1 a lowercase letter that is followed with an uppercase one, and inside the callback, we check if Group 1 matched (with group1 ?). If it matched, we return the group1 + a space. If not, we matched the year at the end, and remove it.
Try this:
"WonderWorld 2016".replace(/([A-Z])|\b[0-9]{4}\b/g, ' $1')
How about this, a single regex to do what you want:
"WonderWorld 2016".replace(/([A-Z][a-z]+)([A-Z].*)\s.*/g, '$1 $2');
"Wonder World"
get everything apart from digits and spaces.
re-code of #Wiktor Stribiżew's solution:
str can be any "WonderWorld 2016" | "OneTwo 1000 ThreeFour" | "Ruby 1999 IamOnline"
str.replace(/([a-z])(?=[A-Z])|\s*\d{4}\b/g, function(m, g) {
return g ? g + " " : "";
});
import re
remove_year_regex = re.compile(r"[0-9]{4}")
Test regex expression here
I am attempting to create a way to convert text with lowercase letters and underscores into text without underscores and the first letter of each word is capitalized.
ex;
options_page = Options Page
At this page: How to make first character uppercase of all words in JavaScript?
I found this regex:
key = key.replace(/(?:_| |\b)(\w)/g, function(key, p1) { return p1.toUpperCase()});
This does everything except replace the underscores with spaces. I have not really tried anything because I am not that familiar with regexpressions.
How can I adjust this regex so it replaces underscores with spaces?
This should do the trick:
function humanize(str) {
var i, frags = str.split('_');
for (i=0; i<frags.length; i++) {
frags[i] = frags[i].charAt(0).toUpperCase() + frags[i].slice(1);
}
return frags.join(' ');
}
console.log(humanize('humpdey_dumpdey'));
// > Humpdey Dumpdey
repl
http://repl.it/OnE
Fiddle:
http://jsfiddle.net/marionebl/nf4NG/
jsPerf:
Most test data: http://jsperf.com/string-transformations
All versions plus _.str: http://jsperf.com/string-transformations/3
Since Lodash 3.1.0, there's a _.startCase([string='']) method that transforms any case into capitalized words (start case):
_.startCase('hello_world'); // returns 'Hello World'
_.startCase('hello-world'); // returns 'Hello World'
_.startCase('hello world'); // returns 'Hello World'
There are other useful methods in the String section of Lodash. Read the documentation here.
These are two different tasks, so two different regexes is the best solution:
key = key.replace(/_/g, ' ').replace(/(?: |\b)(\w)/g, function(key) { return key.toUpperCase()});
To ensure even all capital words is processed. You can add .toLowerCase() before the very first .replace:
console.log('TESTING_WORD'.toLowerCase().replace(/_/g, ' ')
.replace(/(?: |\b)(\w)/g, function(key, p1) {
return key.toUpperCase();
}));
Simply add .replace('_',' ')
Like this
function toCamel(string){
return string.replace(/(?:_| |\b)(\w)/g, function($1){return $1.toUpperCase().replace('_',' ');});
}
Another alternative:
camel = "options_page".replace(/(^|_)(\w)/g, function ($0, $1, $2) {
return ($1 && ' ') + $2.toUpperCase();
});
console.log(camel);
The regular expression:
(^|_) beginning of the input OR "_" ($1)
(\w) a word character (short for [a-zA-Z0-9_]) ($2)
g all occurrences (global)
More about regular expressions : http://www.javascriptkit.com/javatutors/redev.shtml.
Here:
var str = 'Lorem_ipsum_dolor_sit_amet,_consectetur____adipiscing_elit.'
str = str.replace(/_{1,}/g,' ').replace(/(\s{1,}|\b)(\w)/g, function(m, space, letter)
{
return space + letter.toUpperCase();
})
console.log(str);
I have searched for solution but did not find yet.
I have the following string.
1. hello
2. HELLO
3. hello_world
4. HELLO_WORLD
5. Hello World
I want to convert them to following:
1. Hello
2. Hello
3. HelloWorld
4. HelloWorld
5. HelloWorld
If there is No space and underscore in string just uppercase first and all others to lowercase. If words are separated by underscore or space then Uppercase first letter of each word and remove space and underscore. How can I do this in JavaScript.
Thanks
Here is a regex solution:
First lowercase the string:
str = str.toLowerCase();
Replace all _ and spaces and first characters in a word with upper case character:
str = str.replace(/(?:_| |\b)(\w)/g, function(str, p1) { return p1.toUpperCase()})
DEMO
Update: Less steps ;)
Explanation:
/ // start of regex
(?: // starts a non capturing group
_| |\b // match underscore, space, or any other word boundary character
// (which in the end is only the beginning of the string ^)
) // end of group
( // start capturing group
\w // match word character
) // end of group
/g // and of regex and search the whole string
The value of the capturing group is available as p1 in the function, and the whole expression is replaced by the return value of the function.
You could do something like this:
function toPascalCase(str) {
var arr = str.split(/\s|_/);
for(var i=0,l=arr.length; i<l; i++) {
arr[i] = arr[i].substr(0,1).toUpperCase() +
(arr[i].length > 1 ? arr[i].substr(1).toLowerCase() : "");
}
return arr.join("");
}
You can test it out here, the approach is pretty simple, .split() the string into an array when finding either whitespace or an underscore. Then loop through the array, upper-casing the first letter, lower-casing the rest...then take that array of title-case words and .join() it together into one string again.
function foo(str) {
return $(str.split(/\s|_/)).map(function() {
return this.charAt(0).toUpperCase() + this.slice(1).toLowerCase();
}).get().join("");
}
Working demo: http://jsfiddle.net/KSJe3/3/
(I used Nicks regular expression in the demo)
Edit: Another version of the code - I replaced map() with $.map():
function foo(str) {
return $.map(str.split(/\s|_/), function(word) {
return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
}).join("");
}
Working demo: http://jsfiddle.net/KSJe3/4/
An ES6 / functional update of #NickCraver's answer. As with #NickCraver's answer this function will handle multiple spaces / underscores properly by filtering them out.
const pascalWord = x => x[0].toUpperCase() + x.slice(1).toLowerCase();
const toPascalCase2 = (str) => (
str.split(/\s|_/)
.filter(x => x)
.map(pascalWord)
.join('')
);
const tests = [
'hello',
'HELLO',
'hello_world',
'HELLO_WORLD',
'Hello World',
'HELLO__WORLD__',
'Hello World_',
].map(toPascalCase2).join('<br>');
document.write(tests);
var city = city.replace(/\s+/g,' ') //replace all spaceses to singele speace
city = city.replace(/\b\w/g,city => city .toUpperCase()) //after speace letter convert capital