JavaScript - How to underline the first character of every word - javascript

Sentence: Mr Blue has a blue house and a blue car.
JavaScript Code:
`
function myFunction(){
var str = document.getElementById("sentence").innerHTML;
for(var i=0; i<str.length;i++){
if(i == 0 )
{
var res = str.replace(str.charAt(i+1), "<u>"+str.charAt(i+1)+"</u>");
document.getElementById("sentence").innerHTML = res;
}else if(str.charAt(i) == " ")
{
var res = str.replace(str.charAt(i+1), "<u>"+str.charAt(i+1)+"</u>");
document.getElementById("sentence").innerHTML = res;
}
}`
Problem: I am trying to underline the first character in every word of a paragraph when a button is pressed. With the code I have only the C from car is underlined. if anyone can see where I have gone wrong or if there is a better way of doing this problem.
Thanks

Your code is working partially correct. It works on every word of the string but is getting updated again with next word.
You can make it simple by using a regex.
str.replace(/([^\s]+)/g,function(str){
return "<u>"+str.charAt(0)+"</u>" + str.slice(1);
})
Explanation of the regex:
(: Capturing group start
[^: Negated set - Match anything which is not in the set.
\s: Matches any whitespace character (spaces)
]: set ends
): Capturing group ends
Looking at the syntax of the javascript replace function:
str.replace(regexp|substr, newSubstr|function)
function (replacement)
A function to be invoked to create the new substring to be used to
replace the matches to the given regexp or substr. The arguments
supplied to this function are match, submatch, offset and the
original string. (Source: MDN)
Edit: You are still not using the accepted solution in your answer properly. This is how your function will look now:
<script>
function myFunction() {
var str = document.getElementById("Sentence").innerHTML;
var result = str.replace(/([^\s]+)/g,function(str){
return "<u>"+str.charAt(0)+"</u>" + str.slice(1);
});
document.getElementById("Sentence").innerHTML = result;
}
</script>
and if you are comfortable with ES6:
<script>
function myFunction() {
const str = document.getElementById("Sentence").innerHTML;
const result = str.replace(/([^\s]+)/g, p1 => `<u>${p1.charAt(0)}</u>${p1.slice(1)}` );
document.getElementById("Sentence").innerHTML = result;
}
</script>

You store the mutation inside res, but you don't update str, so at the next iteration the previous changes get discarded. Instead just mutate str:
str = str.replace(str.charAt(i+1), "<u>"+str.charAt(i+1)+"</u>");
And then after the loop is done reflect it to the DOM once:
document.getElementById("sentence").innerHTML = str;
How i would solve that:
function underline(selector) {
const el = document.querySelectorAll(selector);
let result = "";
for(const word of el.innerHTML.split(" ")) {
result += `<u>${word[0]}</u>${word.substr(1)}`;
}
el.innerHtML = result;
}
underline("#sentence");

var str = document.getElementById("sentence").innerHTML;
var words = str.match(/\S*/g);
var words2 = [];
words.forEach(function(item, i, arr) {
if (item!="")
{
words2.push(item.replace(item.charAt(1), "<u>"+item.charAt(1)+"</a>"));
}
});
document.getElementById("sentence").innerHTML = words2.join(" ");

Thanks guys for the help, greatly appreciated.
Full Solutions:
<!DOCTYPE html>
<html>
<body>
<p id="Sentence">Mr Blue has a blue house and a blue car.</p>
<button onclick="myFunction()">Click</button>
<script>
function myFunction() {
var str = document.getElementById("Sentence").innerHTML;
var res = str.replace(/([^\s]+)/g,function(str){
return "<u>"+str.charAt(0)+"</u>" + str.slice(1);
});
document.getElementById("Sentence").innerHTML = res;
}
</script>
</body>
</html>

Related

Regular expression not capturing multiple characters [duplicate]

I have a string in JavaScript (e.g., #box2), and I just want the 2 from it.
I tried:
var thestring = $(this).attr('href');
var thenum = thestring.replace(/(^.+)(\w\d+\w)(.+$)/i, '$2');
alert(thenum);
It still returns #box2 in the alert. How can I get it to work?
It needs to accommodate for any length number attached on the end.
For this specific example,
var thenum = thestring.replace(/^\D+/g, ''); // Replace all leading non-digits with nothing
In the general case:
thenum = "foo3bar5".match(/\d+/)[0] // "3"
Here's a bonus: regex generator.
function getre(str, num) {
if(str === num)
return 'nice try';
var res = [/^\D+/g,/\D+$/g,/^\D+|\D+$/g,/\D+/g,/\D.*/g, /.*\D/g,/^\D+|\D.*$/g,/.*\D(?=\d)|\D+$/g];
for(var i = 0; i < res.length; i++)
if(str.replace(res[i], '') === num)
return 'num = str.replace(/' + res[i].source + '/g, "")';
return 'no idea';
};
function update() {
$ = function(x) { return document.getElementById(x) };
var re = getre($('str').value, $('num').value);
$('re').innerHTML = 'Numex speaks: <code>' + re + '</code>';
}
<p>Hi, I'm Numex, the Number Extractor Oracle.
<p>What is your string? <input id="str" value="42abc"></p>
<p>What number do you want to extract? <input id="num" value="42"></p>
<p><button onclick="update()">Insert Coin</button></p>
<p id="re"></p>
You should try the following:
var txt = "#div-name-1234-characteristic:561613213213";
var numb = txt.match(/\d/g);
numb = numb.join("");
alert (numb);​
Result
1234561613213213
I think this regular expression will serve your purpose:
var num = txt.replace(/[^0-9]/g, '');
Where txt is your string.
It basically rips off anything that is not a digit.
I think you can achieve the same thing by using this as well:
var num = txt.replace(/\D/g, '');
Try the following: string.replace(/[^0-9]/g, ''); This will delete all non-digit characters, leaving only digits in the string
function retnum(str) {
var num = str.replace(/[^0-9]/g, '');
return parseInt(num,10);
}
console.log('abca12bc45qw'.replace(/[^0-9]/g, ''));
console.log('#box2'.replace(/[^0-9]/g, ''));
Using the match function.
var thenum = "0a1bbb2".match(/\d+$/)[0];
console.log(thenum);
And this is a snippet which extracts prices with currency and formatting:
var price = "£1,739.12";
parseFloat(price.replace(/[^\d\.]*/g, '')); // 1739.12
I tried all the combinations cited in the previous answer with this code and got it working. It was the only one that worked on that string → (12) 3456-7890
var str = "(12) 3456-7890";
str.replace(/\D+/g, '');
Result: "1234567890"
Obs: I know that a string like that will not be on the attribute, but whatever, the solution is better, because it’s more complete.
You may use the great parseInt() method.
It will convert the leading digits to a number:
parseInt("-10px");
// Will give you -10
You can extract numbers from a string using a regex expression:
let string = "xxfdx25y93.34xxd73";
let res = string.replace(/\D/g, "");
console.log(res);
Output: 25933473
Wrap it into a vanilla JavaScript function:
function onlyNumbers(text){
return text.replace(/\D/g, "");
}
For a string such as #box2, this should work:
var thenum = thestring.replace(/^.*?(\d+).*/,'$1');
jsFiddle:
http://jsfiddle.net/dmeku/
function justNumbers(string)
{
var numsStr = string.replace(/[^0-9]/g, '');
return parseInt(numsStr);
}
console.log(justNumbers('abcdefg12hijklmnop'));
You can do a function like this
function justNumbers(string)
{
var numsStr = string.replace(/[^0-9]/g, '');
return parseInt(numsStr);
}
Remember: if the number has a zero in front of it, the int won’t have it
If you want to parse a number from a price like $6,694.20, it can be done this way:
parseFloat('$6,694.20'.replace(/^\D|,+/g, ''))
Or via a function:
function parsePrice(value) {
return parseFloat(value.replace(/^\D|,+/g, ''))
}
parsePrice('$6,694.20') // 6694.2
To return an int from the string, you can do the following code. It removes all not number characters and returns an integer.
Number("strin[g]3".replace(/\D+/g, ""))
You can use a regular expression.
var txt="some text 2";
var numb = txt.match(/\d/g);
alert (numb);
That will alert 2.
let str = "Total Work Duration: 189.56 Hrs.Present: 23.5 Absent: 2";
/* The provided regex globally matches the character
"." and a digit from the string */
let numArr = str.match(/[\d\.]+/g)
/* It returns an array [189.56, ., 23.5, 2], and
uses the filter function to remove the '.' */
numArr = numArr.filter(n => n != '.')
console.log(numArr)
If someone need to preserve dots in extracted numbers:
var some = '65,87 EUR';
var number = some.replace(",",".").replace(/[^0-9&.]/g,'');
console.log(number); // returns 65.87
You can use Underscore.js' string library as follows:
var common = "#box"
var href = "#box1"
_(href).strRight(common)
The result will be: 1
See: Underscore.string
Demo:
http://jsfiddle.net/abdennour/Vyqtt/
HTML code:
<p>
<a href="#box1" >img1</a>
<a href="#box2" >img2</a>
<a href="#box3" >img3</a>
<a href="#box4" >img4</a>
</p>
<div style="font-size:30px"></div>
JavaScript code:
var comm = "#box"
$('a').click(function() {
$('div').html(_($(this).attr('href')).strRight(comm))})
If you have a suffix as follows:
href="box1az"
You can use the following demo:
http://jsfiddle.net/abdennour/Vyqtt/1/
function retrieveNumber(all, prefix, suffix) {
var left = _(all).strRight(prefix);
return _(left).strLeft(suffix);
}
Here's a solution that checks for no data:
var someStr = 'abc'; // Add 123 to string to see the inverse
var thenum = someStr.match(/\d+/);
if (thenum != null)
{
console.log(thenum[0]);
}
else
{
console.log('Not a number');
}
var elValue = "-12,erer3 4,-990.234sdsd";
var isNegetive = false;
if(elValue.indexOf("-") == 0)
isNegetive = true;
elValue = elValue.replace( /[^\d\.]*/g, '');
elValue = isNaN(Number(elValue)) ? 0 : Number(elValue);
if(isNegetive)
elValue = 0 - elValue;
alert(elValue); // -1234990.234
With regular expressions, how to get numbers from a string, for example:
String myString = "my 2 first gifts were made by my 4 brothers";
myString = myString.replaceAll("\\D+", "");
System.out.println("myString: " + myString);
The result of myString is "24".
You can see an example of this running code at http://ideone.com/iOCf5G.
Use this one-line code to get the first number in a string without getting errors:
var myInt = parseInt(myString.replace(/^[^0-9]+/, ''), 10);
Please check the below JavaScript code. There you can get only a number.
var txt = "abc1234char5678#!9";
var str = txt.match(/\d+/g, "") + '';
var s = str.split(',').join('');
alert(Number(s));
Output: 1234567789
You need to add "(/\d+/g)" which will remove all non-number text, but it will still be a string at this point. If you create a variable and "parseInt" through the match, you can set the new variables to the array values. Here is an example of how I got it to work:
var color = $( this ).css( "background-color" );
var r = parseInt(color.match(/\d+/g)[0]);
var g = parseInt(color.match(/\d+/g)[1]);
var b = parseInt(color.match(/\d+/g)[2]);
This answer will cover most of the scenarios. I came across this situation when a user tried to copy paste the phone number.
$('#help_number').keyup(function() {
$(this).val().match(/\d+/g).join("")
});
Explanation:
str = "34%^gd 5-67 6-6ds"
str.match(/\d+/g)
It will give an array of strings as output:
["34", "56766"]
 
str.match(/\d+/g).join("")
join() will convert and concatenate that array data into a single string.
Output:
"3456766"
In my example, I needed the output as 209-356-6788, so I used replace():
$('#help_number').keyup(function() {
$(this).val($(this).val().match(/\d+/g).join("").replace(/(\d{3})\-?(\d{3})\-?(\d{4})/, '$1-$2-$3'))
});
Written without a regular expression:
// Without Regex
function extractNumber(string) {
let numArray = string.split('').map(item => {
if (typeof +item === 'number' && !isNaN(+item))
return +item
})
return +numArray.join('')
}
extractNumber('#1200milion$') // 1200
In one of my projects I had to take a rating value from a string. This is what I used:
let text = '#xbox2'
let num = text.trim().
split('').
map(num => Number(num)).
filter(x => Number.isInteger(x))
Use:
changeStrangeDate(dateString: string) {
var sum = 0;
var numbers = dateString.match(/\d+/g);
if (numbers.length > 1) {
numbers.forEach(element => {
sum += parseInt(element);
}
);
}
console.log(new Date(sum).toDateString());
return new Date(sum).toUTCString();
}
You can do it like that and then call a function where you need it, with a parameter.
this.changeStrangeDate('/Date(1551401820000-0100)/');

Split sentence by space mixed up my index

I'm facing some problem while trying to send text to some spelling API.
The API return the corrections based on the words index, for example:
sentence:
"hello hoow are youu"
So the API index the words by numbers like that and return the correction based on that index:
0 1 2 3
hello hoow are youu
API Response that tell me which words to correct:
1: how
3: you
On the code I using split command to break the sentence into words array so I will be able to replace the misspelled words by their index.
string.split(" ");
My problem is that the API trim multiple spaces between words into one space, and by doing that the API words index not match my index. (I would like to preserve the spaces on the final output)
Example of the problem, sentence with 4 spaces between words:
Hello howw are youu?
0 1 2 3 4 5 6 7
hello hoow are youu
I thought about looping the words array and determine if the element is word or space and then create something new array like that:
indexed_words[0] = hello
indexed_words[0_1] = space
indexed_words[0_2] = space
indexed_words[0_3] = space
indexed_words[0_4] = space
indexed_words[0_5] = space
indexed_words[0_6] = space
indexed_words[0_7] = space
indexed_words[1] = how
indexed_words[2] = are
indexed_words[3] = you?
That way I could replace the misspelled words easily and than rebuild the sentence back with join command but the problem but the problem that I cannot use non-numeric indexes (its mixed up the order of the array)
Any idea how I can keep the formatting (spaces) but still correct the words?
Thanks
in that case you have very simple solution:L
$(document).ready(function(){
var OriginalSentence="howw are you?"
var ModifiedSentence="";
var splitstring=OriginalSentence.split(' ')
$.each(splitstring,function(i,v){
if(v!="")
{
//pass this word to your api and appedn it to sentance
ModifiedSentence+=APIRETURNVALUE//api return corrected value;
}
else{
ModifiedSentence+=v;
}
});
alert(ModifiedSentence);
});
Please review this one:
For string manipulation like this, I would highly recommend you to use Regex
Use online regex editor for faster try and error like here https://regex101.com/.
here I use /\w+/g to match every words if you want to ignore 1 or two words we can use /\w{2,}/g or something like that.
var str = "Hello howw are youu?";
var re = /\w+/g
var words = str.match(re);
console.log("Returning valus")
words.forEach(function(word, index) {
console.log(index + " -> " + word);
})
Correction
Just realize that you need to keep spacing as it is, please try this one:
I used your approach to change all to space. create array for its modified version then send to your API (I dunno that part). Then get returned data from API, reconvert it back to its original formating string.
var ori = `asdkhaskd asdkjaskdjaksjd askdjaksdjalsd a ksjdhaksjdhasd asdjkhaskdas`;
function replaceMeArr(str, match, replace) {
var s = str,
reg = match || /\s/g,
rep = replace || ` space `;
return s.replace(reg, rep).split(/\s/g);
}
function replaceMeStr(arr, match, replace) {
var a = arr.join(" "),
reg = match || /\sspace\s/g,
rep = replace || " ";
return a.replace(reg, rep);
}
console.log(`ori1: ${ori}`);
//can use it like this
var modified = replaceMeArr(ori);
console.log(`modi: ${modified.join(' ')}`);
//put it back
var original = replaceMeStr(modified);
console.log(`ori2: ${original}`);
Updated
var str = "Hello howw are youu?";
var words = str.split(" ");
// Getting an array without spaces/empty values
// send it to your API call
var requestArray = words.filter(function(word){
if (word) {
return word;
}
});
console.log("\nAPI Response that tell me which words to correct:");
console.log("6: how\n8: you");
var response = {
"1": "how",
"3": "you"
}
//As you have corrected words index, Replace those words in your "requestArray"
for (var key in response) {
requestArray[key] = response[key];
}
//now we have array of non-empty & correct spelled words. we need to put back empty (space's) value back in between this array
var count = 0;
words.forEach(function(word, index){
if (word) {
words[index] = requestArray[count];
count++;
}
})
console.log(words);
Correct me, if i was wrong.
Hope this helps :)
Try this JSFiddle
, Happy coding :)
//
// ReplaceMisspelledWords
//
// Created by Hilal Baig on 21/11/16.
// Copyright © 2016 Baigapps. All rights reserved.
//
var preservedArray = new Array();
var splitArray = new Array();
/*Word Object to preserve my misspeled words indexes*/
function preservedObject(pIndex, nIndex, title) {
this.originalIndex = pIndex;
this.apiIndex = nIndex;
this.title = title;
}
/*Preserving misspeled words indexes in preservedArray*/
function savePreserveIndexes(str) {
splitArray = str.split(" ");
//console.log(splitArray);
var x = 0;
for (var i = 0; i < splitArray.length; i++) {
if (splitArray[i].length > 0) {
var word = new preservedObject(i, x, splitArray[i]);
preservedArray.push(word);
x++;
}
}
};
function replaceMisspelled(resp) {
for (var key in resp) {
for (var i = 0; i < preservedArray.length; i++) {
wObj = preservedArray[i];
if (wObj.apiIndex == key) {
wObj.title = resp[key];
splitArray[wObj.originalIndex] = resp[key];
}
}
}
//console.log(preservedArray);
return correctedSentence = splitArray.join(" ");
}
/*Your input string to be corrected*/
str = "Hello howw are youu";
console.log(str);
savePreserveIndexes(str);
/*API Response in json of corrected words*/
var apiResponse = '{"1":"how","3":"you" }';
resp = JSON.parse(apiResponse);
//console.log(resp);
/*Replace misspelled words by corrected*/
console.log(replaceMisspelled(resp)); //Your solution

replace multiple words using javascript?

I am using the following code to replace one word by an empty space in an input field.
however, I want to be able to replace multiple words with empty space.
basically I need to create a word filter so the users can't type certain words.
HTML CODE
<input type="text" id="demo" name="demo" onkeyup="myFunction()" onkeydown="myFunction()" />
Javascript code:
<script>
function myFunction() {
var words = "badword1";
var str = document.getElementById("demo").value;
var res = str.replace(words, " ");
document.getElementById("demo").value = res;
}
</script>
I've tried something like this:
<script>
function myFunction() {
var words = "badword1 || badword2 || bad word3";
var str = document.getElementById("demo").value;
var res = str.replace(words, " ");
document.getElementById("demo").value = res;
alert('that word is not allowed!');
}
</script>
but this doesn't work.
first, it doesn't replace any given badword(s) with empty space and second it fires the aler(); message as soon as I type the first letter in the input field!
could someone please help me out with this?
something like this takes the array of bad words... loops through them creates a global regex that then is used to replace it... compares the original and resulting string if they changed put alert.
var badwords = ['badword1','badword2','badword3']; //array of badwords
function myFunction() {
var str = document.getElementById("demo").value;
var res = str;
for (var i = badwords.length - 1; i >= 0; i--) {
var badword = badwords[i];
badWordRegex = new RegExp(badword, 'g');
res=res.replace(badWordRegex, " ");
};
document.getElementById("demo").value = res;
if (str !== res){
alert('that word is not allowed!');
}
}
Use regex:
var words = new RegExp("badword1|badword|bad word3", g);
ACtually you shouldn't trust client-side code...

Regex to capture Ids from text

I have the following regex where I am trying to capture the Ids of each start comment. But for some reason I am only able to capture the first one. It won't grab the Id of the nested comment. It only prints 1000 to the console. I am trying to get it to capture both 1000 and 2000. Can anyone spot the error in my regex?
<script type="text/javascript">
function ExtractText() {
var regex = /\<!--Start([0-9]{4})-->([\s\S]*?)<!--End[0-9]{4}-->/gm;
var match;
while (match = regex.exec($("#myHtml").html())) {
console.log(match[1]);
}
}
</script>
<div id="myHtml">
<!--Start1000-->Text on<!--Start2000-->the left<!--End1000-->Text on the right<!--End2000-->
</div>
Based on Mike Samuel's answer I updated my JS to the following:
function GetAllIds() {
var regex = /<!--Start([0-9]{4})-->([\s\S]*?)<!--End\1-->/g;
var text = $("#myHtml").html();
var match;
while (regex.test(text)) {
text = text.replace(
regex,
function (_, id, content) {
console.log(id);
return content;
});
}
}
In
<!--Start1000-->Text on<!--Start2000-->the left<!--End1000-->Text on the right<!--End2000-->
the "1000" region overlaps the "2000" region, but the exec loop only finds non-overlapping matches since each call to exec with the same regex and string starts at the end of the last match. To solve this problem, try
var regex = /<!--Start([0-9]{4})-->([\s\S]*?)<!--End\1-->/g;
for (var s = $("#myHtml").html(), sWithoutComment;
// Keep going until we fail to replace a comment bracketed chunk
// with the chunk minus comments.
true;
s = sWithoutComment) {
// Replace one group of non-overlapping comment pairs.
sWithoutComment = s.replace(
regex,
function (_, id, content) {
console.log(id);
// Replace the whole thing with the body.
return content;
});
if (s === sWithoutComment) { break; }
}
You can use grouping and then another regexp:
var regex = /(<!--Start)([0-9]{4})/ig;
var str = document.getElementById('myHtml').innerHTML;
var matches = str.match(regex);
for(var i=0;i<matches.length;i++){
var m = matches[i];
var num = m.match(/(\d+)/)[1];
console.log(num);
}

Uppercase first letter of variable

I have searched over the web and I can't find anything to help me. I want to make the first letter of each word upper case within a variable.
So far I have tried:
toUpperCase();
And I didn't have any luck, as it uppercases all letters.
Use the .replace function to replace the lowercase letters that begin a word with the capital letter.
var str = "hello, world!";
str = str.toLowerCase().replace(/\b[a-z]/g, function(letter) {
return letter.toUpperCase();
});
alert(str); //Displays "Hello, World!"
If you are dealing with word characters other than just a-z, then the following (more complicated) regular expression might better suit your purposes.
var str = "петр данилович björn über ñaque αλφα";
str = str.toLowerCase().replace(/^[\u00C0-\u1FFF\u2C00-\uD7FF\w]|\s[\u00C0-\u1FFF\u2C00-\uD7FF\w]/g, function(letter) {
return letter.toUpperCase();
});
alert(str); //Displays "Петр Данилович Björn Über Ñaque Αλφα"
A much easier way:
$('#test').css('textTransform', 'capitalize');
I have to give Rafael Herscovici some credit for leading me down the right path. It is far simpler than whatever you guys are proposing.
http://phpjs.org/functions/ucwords:569 has a good example
function ucwords (str) {
return (str + '').replace(/^([a-z])|\s+([a-z])/g, function ($1) {
return $1.toUpperCase();
});
}
(omitted function comment from source for brevity. please see linked source for details)
EDIT: Please note that this function uppercases the first letter of each word (as your question asks) and not just the first letter of a string (as your question title asks)
Here is a pure JavaScript solution (no jQuery):
function capitalize(str) {
strVal = '';
str = str.split(' ');
for (var chr = 0; chr < str.length; chr++) {
strVal += str[chr].substring(0, 1).toUpperCase() + str[chr].substring(1, str[chr].length) + ' '
}
return strVal
}
console.log(capitalize('hello world'));
I imagine you could use substring() and toUpperCase() to pull out the first character, uppercase it, and then replace the first character of your string with the result.
myString = "cheeseburger";
firstChar = myString.substring( 0, 1 ); // == "c"
firstChar.toUpperCase();
tail = myString.substring( 1 ); // == "heeseburger"
myString = firstChar + tail; // myString == "Cheeseburger"
I think that should work for you. Another thing to consider is that if this data is being displayed, you can add a class to its container that has the CSS property "text-transform: capitalize".
To do this, you don't really even need JavaScript if you're going to use
$('#test').css('text-transform', 'capitalize');
Do this as CSS like:
#test,h1,h2,h3 { text-transform: capitalize; }
Or do it as a class and apply that class to wherever you need it:
.ucwords { text-transform: capitalize; }
It is as simple as the following:
string = 'test';
newString = string[0].toUpperCase() + string.slice(1);
alert(newString);
Ever heard of substr()?
For a starter:
$("#test").text($("#test").text().substr(0,1).toUpperCase()+$("#test").text().substr(1,$("#test").text().length));
Thanks to #FelixKling for the tip:
$("#test").text(function(i, text) {
return text.substr(0,1).toUpperCase() + text.substr(1);
});
Building on Peter Olson's answer, I took a more object-oriented approach without jQuery:
String.prototype.ucwords = function() {
return this.toLowerCase().replace(/\b[a-z]/g, function(letter) {
return letter.toUpperCase();
});
}
alert("hello, world!".ucwords()); // Displays "Hello, World!"
Example: http://jsfiddle.net/LzaYH/1/
The simplest way
let str = "hiren raiyani"
str.toLowerCase().replace(/(?<= )[^\s]|^./g, a => a.toUpperCase());
User-defined function:
function capitalize(str){
return str.toLowerCase().replace(/(?<= )[^\s]|^./g, a => a.toUpperCase());
}
Output: Hiren Raiyani
Use code as your user-defined function or direct.
var mystring = "hello World"
mystring = mystring.substring(0,1).toUpperCase() +
mystring.substring(1,mystring.length)
console.log(mystring) //gives you Hello World
var ar = 'foo bar spam egg'.split(/\W/);
for(var i=0; i<ar.length; i++) {
ar[i] = ar[i].substr(0,1).toUpperCase() + ar[i].substr(1,ar[i].length-1)
}
ar.join(' '); // Foo Bar Spam Egg
You can try this simple code with the features of ucwords in PHP.
function ucWords(text) {
return text.split(' ').map((txt) => (txt.substring(0, 1).toUpperCase() + txt.substring(1, txt.length))).join(' ');
}
ucWords('hello WORLD');
It will keep the Upper Cases unchanged.
You can use text-transform: capitalize; for this work.
HTML
<input type="text" style="text-transform: capitalize;" />
jQuery
$(document).ready(function (){
var asdf = "WERTY UIOP";
$('input').val(asdf.toLowerCase());
});
Try This
Note: It's only changing the visual representation of the string. If you alert() this string, it will always show the original value of the string.
Based completely on Rafael Herscovici's answer, this solution is ready to call with a simple jQuery method, 'ucwords'...
$.extend({
ucwords : function(str) {
strVal = '';
str = str.split(' ');
for (var chr = 0; chr < str.length; chr++) {
strVal += str[chr].substring(0, 1).toUpperCase() + str[chr].substring(1, str[chr].length) + ' '
}
return strVal
}
});
Example:
This can be called using the method
var string = "this is a test";
string = $.ucwords(string); // Returns "This Is A Test"
Without JQuery
String.prototype.ucwords = function() {
str = this.trim();
return str.replace(/(^([a-zA-Z\p{M}]))|([ -][a-zA-Z\p{M}])/g, function(s){
return s.toUpperCase();
});
};
console.log('hello world'.ucwords()); // Display Hello World
Short and simple answer:
let str = 'this is a string';
let result = str.replace(/\b\w/g, x => x.toUpperCase());
console.log(result); // This Is A String
The easiest way to uppercase the first letter in JavaScript
var string = "made in india";
string = string.toLowerCase().replace(/\b[a-z]/g, function(letter){return letter.toUpperCase();});
alert(string);
Result:
"Made In India"
Use the below function:
const capitalize = (s) => {
if (typeof s !== 'string')
return ''
return s.charAt(0).toUpperCase() + s.slice(1)
}
capitalize('test') // 'Test'
capitalize('name') // 'Name'
I have used this code -
function ucword(str){
str = str.toLowerCase().replace(/(^([a-zA-Z\p{M}]))|([ -][a-zA-Z\p{M}])/g, function(replace_latter) {
return replace_latter.toUpperCase();
}); //Can use also /\b[a-z]/g
return str; //First letter capital in each word
}
var uc = ucword("good morning. how are you?");
alert(uc);
There sure are a lot of ways to do this!
One thing that I think people forget is that strings are arrays of characters. So, the first letter of any string will be the 'zeroth' element of its array:
let word = 'interesting';
console.log(word[0]);
// 'i'
The simplest way to take advantage of this fact for the purpose of uppercasing the first letter (afaik) would be:
let word = 'interesting';
let titleCase = word[0].toUpperCase() + word.substr(1);
console.log(titleCase);
// 'Interesting'
...or as a function:
function toTitleCase(word) {
return word[0].toUpperCase() + word.substr(1);
}
I think, the method should not convert any other letters than just the very first or the very first of any letter.
My solution for that are the following regexes:
function capitalize( str ){
return str.replace(/^\w/, (s) => s.toUpperCase() );
}
function capitalizeAll( str ){
return str.replace(/(\b\w)/g, (s) => s.toUpperCase() );
}
let test = 'hello world';
capitalize( test ); // Hello world
capitalizeAll( test ); // Hello World
The string to lower before capitalizing the first letter.
(Both use jQuery syntax)
function CapitaliseFirstLetter(elementId) {
var txt = $("#" + elementId).val().toLowerCase();
$("#" + elementId).val(txt.replace(/^(.)|\s(.)/g, function($1) {
return $1.toUpperCase();
}));
}
In addition a function to Capitalise the WHOLE string:
function CapitaliseAllText(elementId) {
var txt = $("#" + elementId).val();
$("#" + elementId).val(txt.toUpperCase());
}
Syntax to use on a textbox's click event:
onClick="CapitaliseFirstLetter('TextId'); return false"
var str = "HELLO WORLD HELLO WORLD HELLO WORLD HELLO WORLD";
str = str.replace(
/([A-Z])([A-Z]+)/g,
function (a, w1, w2) {
return w1 + w2.toLowerCase();
});
alert(str);
Here is Unicode-safe ucwords() function, which additionally respects double-lastnames like Russian Засс-Ранцев and some noble names like Honoré de Balzac, d'Artagnan, Vincent van Gogh, Otto von Bismarck, Sulaymān ibn Dāwūd, etc.:
String.prototype.ucwords = function() {
return this.toLowerCase()
.replace(/(^|\s|\-)[^\s$]/g, function(m) {
return m.toUpperCase();
})
// French, Arabic and some noble names...
.replace(/\s(Of|De|Van|Von|Ibn|Из|Ван|Фон|Ибн)\s/g, function(m) { // Honoré de Balzac, Vincent van Gogh, Otto von Bismarck, Sulaymān ibn Dāwūd etc.
return m.toLowerCase();
})
.replace(/(^|\s)(D|Д)(['’][^\s$])/g, function(m, p1, p2, p3) { // D'Artagnan or d'Artagnan / Д’Артаньян или д’Артаньян
return p1 + (p1 === "" ? p2/*.toUpperCase()*/ : p2.toLowerCase()) + p3.toUpperCase();
});
}
var country = $('#country').val();
var con = country[0].toUpperCase();
ctr = country.replace(country[0], con);
There isn't any need to create any function, just jugaaar.
HTML:
<input class="capitalize" name="Address" type="text" value="" />
JavaScript with jQuery:
$(".capitalize").bind("keyup change", function (e) {
if ($(this).val().length == 1)
$(this).val($(this).val().toUpperCase());
$(this).val($(this).val().toLowerCase().replace(/\s[\p{L}a-z]/g, function (letter) {
return letter.toUpperCase();
}))
});

Categories

Resources