How to do Trim operation in javascript - javascript

I need to trim a text that has been entered in a text box using Java Script
before saving it in DB in asp.net.
Thanks

String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
}
var text = " fdsfsdf ";
text = text.trim();

You can add a trim function to your toolset :
Function trim (str) {
return str.replace(/^\s+/g,'').replace(/\s+$/g,'')
}
Ans use it like this :
var trimmed = str.trim();
Note that if you use jquery, you can use the included trim function.

function trim(stringToTrim) {
return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function ltrim(stringToTrim) {
return stringToTrim.replace(/^\s+/,"");
}
function rtrim(stringToTrim) {
return stringToTrim.replace(/\s+$/,"");
}
// example of using trim, ltrim, and rtrim
var myString = " hello my name is ";
alert("*"+trim(myString)+"*");
alert("*"+ltrim(myString)+"*");
alert("*"+rtrim(myString)+"*");

If you don't need to support IE <= 8, javascript already has String.prototype.trim:
" hello ".trim() //"hello";

Related

find text in string and replace it

I have a variable which contains a string expression. This expression have the pattern:
propery_expression operator value
proeprty_expression can look like:
World
World/Name
City/Name
I want to find text after /, and If it exists, and replace with custom text. How can I do this?
With a regex, for example this one :
yourString.replace(/\/\S+/, '/the new stuff...');
In the console :
> var cityName = 'Djakarta';
> var line = 'World/Name Something SomethingElse';
> line.replace(/\/\S+/, '/' + cityName);
"World/Djakarta Something SomethingElse"
You can use this to do complex search and replace operations. Details on Mozilla's documentation
You could try this
var the_string = "City/Name";
var word = "New";
var result = the_string.substring(0, the_string.lastIndexOf('/') + 1);
alert(result + word);
You can try this:
var str = 'World';
alert(rep(str));
function rep(str)
{
if(str.indexOf('/')>-1)//present
{
alert(str.substring(str.lastIndexOf('/') + 1,str.length));
var res = str.replace(str.substring(str.lastIndexOf('/') + 1,str.length),'custom_word');
return res;
}
else{
alert(' / not present');
return str;
}
}
DEMO
Note: If text present after / then it replace it with "custom_word".
In addition to Mathias's answer, you could use RegEx together with a function, like so:
var myString;
.
.
.
myString.replace(/\/(\S+)/g, function (found, value) {
// found == "City/NewYork"
// value == "NewYork"
return found + "Altered";
}
This, for example, will change every "x/y" with "x/yAltered"

How to remove the comma(,) from the first position and last position of string

I want to remove the comma(,) from the the string if it occur at first position or last position in the string.
For Example :
var str = ",abcd,efg,last,";
The output should be
output = 'abcd,efg,last'
if input is
str = "abcdef,ghij,kl"
the output should be :
output = "abcdef,ghij,kl"
var str = ",abcd,efg,last,";
var res = str.replace(/^,|,$/g, '');
console.log(res);
do this
this will remove the comma if it is at the starting position or at the end of the string position
There must be some strip() function in Javascript that I don't know for lack of my knowledge. But here is how you can do it using regex:
output = ",abcd,efg,last,".replace(/^,|,$/g, "");
JavaScript doesn't include a native method for this. The closest is trim, but that doesn't take any args. I think it should, though. So you could write something like this
String.prototype.trim = (function (trim) {
if (!trim) // polyfill if not included in browser
trim = function () {
return this.replace(/^\s+|\s+$/g, '');
};
else if (trim.call('.', '.') === '') // already supports this
return trim;
return function (chars) {
if (!chars) return trim.call(this);
chars = chars.replace(/([\^\\\]-])/g, '\\$1');
return this.replace(new RegExp('^['+chars+']+|['+chars+']+$', 'g'), '');
}
}(String.prototype.trim));
Now we have
' foo '.trim(); // "foo"
',,,foo,,,'.trim(','); // "foo"

Trim blank spaces from the right in jQuery

I see the trim method in jQuery, but I can't find, in its documentation, how to trim blank spaces from only the right of the string.
As an example, if I have:
"foobar " "foo " " foo bar "
Trimming the spaces from the right of the string results in:
"foobar" "foo" " foo bar"
Is there any method in jQuery to trim the spaces from the right? I mean, something like ltrim and rtrim?
You can use a simple regex replace
string.replace(/\s+$/, '')
Demo: Fiddle
function rtrim(str){
return str.replace(/\s+$/, '');
}
jQuery doesn't have the methods ltrim or rtrim.
You can do it easily:
function rtrim(str){
return str.replace(/\s+$/, "");
}
function ltrim(str){
return str.replace(/^\s+/, "");
}
I don't suggest you add a method on the String prototype.
you could do:
String.prototype.rtrim = function() {
return this.replace(/\s+$/,"");
}
var str = "test ";
console.log(str.rtrim());
You can do something like this too:
"foobar ".substring(0,"foobar ".length-1)
I'm not really into jQuery so you may need to use
var yourstring ="something ";

Javascript to Trim spaces when enter value in text box

I am currently trying to show one text box value in another using javascript function
function fillTextbox() {
var txtCompanyName = document.getElementById("txtCompanyName").value;
document.getElementById("txtSecureSite").value = txtCompanyName;
}
and i successfully done this but now i want to trim spaces when my user enters a name with spaces. Please help as i am new in javascript.
Use string.trim()
document.getElementById("txtSecureSite").value = txtCompanyName.toString().trim();
From MDN
Running the following code before any other code will create
String.trim if it's not natively available.
if(!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g,'');
};
}
You can trim any string value like this:
" string ".trim(); // outputs: "string"
Based on: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/Trim
Or use jQuery.trim() instead:
$.trim(" string "); // outputs: "string"
Use replace(/(^\s+|\s+$)/g, '') to remove spaces from the begining and end of the string.
function fillTextbox() {
var txtCompanyName = document.getElementById("txtCompanyName").value;
var company = txtCompanyName.replace(/(^\s+|\s+$)/g, '');
document.getElementById("txtSecureSite").value = company;
}
Try :
function fillTextbox() {
var txtCompanyName = document.getElementById("txtCompanyName").value;
var company = txtCompanyName.replace(/\s/g, "");
document.getElementById("txtSecureSite").value = company;
}
var orig = " foo ";
alert(orig.trim());
In your case:
var txtCompanyName = document.getElementById("txtCompanyName").value;
txtCompanyName = txtCompanyName.toString().trim();
See Trim() in javascript
Keep it simple, try this 👇
var CompanyName = document.getElementById("txtCompanyName"),
CompanyNameTrimmed = CompanyName.value.trim(),

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