Trim blank spaces from the right in jQuery - javascript

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 ";

Related

Invert brace from { to } and vise versa

I have a string with { and } how can I take all of them and reverse them, so all { become } and } become {?
I can't do this:
str = str.replace("}", "{");
str = str.replace("{", "}");
because that will make A face the same way as B then it will replace B which will all change them to the same direction.
I tried doing this:
str = str.replace(["{", "}"], ["}", "{"]);
But that just doesn't seem to do anything (not even error out).
So, what can I do to invert them?
You could use a regexp with a callback function to solve this:
str.replace(/\{|\}/g, function(match) {
return match == "}" ? "{" : "}";
});
You can use a temporary string that will definitely be unique to do the swap:
str = str.replace("}", "TEMP_HOLDER");
str = str.replace("{", "}");
str = str.replace("TEMP_HOLDER", "{");
But it's prone to a bug if the string contains the temp string and it also doesn't replace more than one occurrence. I'd suggest using Erik's answer.
You need to convert to something else in the first pass, and then convert to what you want after you've made the other conversions.
str = str.replace("{", "_###_");
str = str.replace("}", "{");
str = str.replace("_###_", "}");
Of course, the something else will need to be something that won't otherwise be in your string. You could use "\r\n" if you are sure you string won't contain newlines.
You could go with a two stage solution:
str = str.replace("}", "~");
str = str.replace("{", ",");
str = str.replace("~", "{");
str = str.replace(",", "}");

return value from string prototype using javascript

I am using prototype method to replace comma in string but the function giving same string
String.prototype.removeLastComma = function(){
return this.replace(/,/g, '.');
}
String.prototype.removeLastComma = function(){
return this.replace(/,/g, '.');
}
Works just fine. I guess you're expecting the following effect:
var str = 'foo,bar,baz';
str.removeLastComma();
console.log(str); //foo.bar.baz
Unfortunately, this is not possible because the strings in JavaScript are immutable.
Try this instead:
var str = 'foo,bar,baz';
str = str.removeLastComma();
console.log(str); //foo.bar.baz
NOTE: better call your method "removeCommas" or something like that. Remove last comma means that you're going to remove only the last one.
For removing the last comma you can use the following regular expression:
String.prototype.removeLastComma = function(){
return this.replace(/,(?=[^,]*$)/, '.');
}
it works fine for me. For a sample implementation see: http://jsfiddle.net/9Hrzp/
String.prototype.removeLastComma = function(){
return this.replace(/,/g, '.');
}
alert("foo,bar".removeLastComma());

Replace function of JavaScript don't work

I have next code in javascript:
csvReport.name = "My New Report";
$scope.filename = csvReport.name.replace(" ", "_");
But I get $scope.filename = My_New Report. Not all spaces replacing.
What is it?
.replace will always replace the first occurence except if you use regular expression like that :
csvReport.name.replace(/ /g, "_");
You can use replace with a regular expression :
"My New Report".replace(/ /g,'_')
Demo
You can use regular expression with a global switch (g) to actually replace all instances, like this:
csvReport.name = "My New Report";
$scope.filename = csvReport.name.replace(/ /g, "_");
Function replace only replace first appearance of first argument. You can use regular expression to replace in whole string.
Try this:
if (!String.replaceAll) {
String.prototype.replaceAll = function(replace, value) {
var regexpStr = replace.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&")
return this.replace(new RegExp(regExpStr, 'g'), value);
};
}
This way you have additional function that works on whole string.

Splitting string by whitespace, without empty elements?

I am trying to explode an string using javascript to pick searchterms, whitespace-separated. However I get empty array elements if a searchterm is ended by a whitespace, as shown below.
What should I do instead to avoid post-processing this array and removing empty elements?
var str = "searchterm1 searchterm2";
console.log(str.split(" ")); // ["searchterm1", "searchterm2"]
var strb = "searchterm1 "; // Note the ending whitespace
console.log(strb.split(" ")); // ["searchterm1", ""]
You could simply match all non-space character sequences:
str.match(/[^ ]+/g)
No matter what splitter this always works:
str.split(' ').filter(function(i){return i})
// With ES6
str.split(' ').filter(i => i)
Filter logic also can change in some other cases.
This is a bit old, but for documentation purposes there is also another neat way.
someString.filter(Boolean);
// Example
['fds', '', 'aaaaa', 'AA', 'ffDs', "", 'd'].filter(Boolean);
// Output
["fds", "aaaaa", "AA", "ffDs", "d"]
Edit
How does it work ?
The following are identical
.filter(Boolean)
.filter((value) => Boolean(value))
Boolean() as function behave as a converter of any type to Boolean by the standard input to output.
References:
Global Objects -> Boolean
Truthy
Falsy
This is the simplest solution IMO. trim() first to get rid of leading/trailing whitespace, then split by whitespace.
function split(str) {
return str.trim().split(/\s+/);
}
console.log(split('foo bar baz'));
console.log(split(' foo bar baz '));
If you want a function that you can use, just extend String:
String.prototype.splitNoSpaces = function(){
return this.split(' ').filter(function(i){return i});
};
//Now use it!
var classString = "class1 class2 class3 class4";
var classArray = classString.splitNoSpaces();
//classArray[0] is class1
//classArray[1] is class2
//classArray[2] is class3
//classArray[3] is class4
Thanks to #user1079877 for the hint
Add function:
//Some browsers support trim so we check for that first
if(!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g,'');
};
}
Then call trim on the string:
var strb = "searchterm1 "; // Note the ending whitespace
console.log(strb.trim().split(" ")); // ["searchterm1"]

is it possible in javascript to include other characters in jquery.Trim()

i have a string that might look like one of these and i want to display this string on the page but remove all trailing characters (spaces, commas . )
var string1 = "test, test1, test2, test3, ";
var string2 = "test, test1, test2, test3 ";
var string3 = "test, test1, test2, test3";
if i use jquery.Trim() that will work for string2 and string3 but i want a solution that will remove the trailing comman from string1 as well.
what is the best way to do this in javascript, jquery ??
Internally, jQuery.trim uses two variables:
trimLeft = /^\s+/,
trimRight = /\s+$/,
which is private to the jQuery function so you can't change them (which is a good thing because other code may depend on jQuery.trim working the way it does).
But you can easily make your own trim function with the semantics that you need, even as a jQuery plugin:
// your plugin:
jQuery.trimCommas = function(text) {
return text == null ?
"" :
text.toString().replace(/^[\s,]+|[\s,]+$/g, "");
};
// your code:
var string1 = "test, test1, test2, test3, ";
alert($.trimCommas(string1));
See this fiddle: http://jsfiddle.net/Nwsur/
The easiest way to do this is with regular expressions.
your_string = your_string.replace(/,?\s+$/, "");
If you want to use this everywhere you can update $.trim to take a regular expression in this manner:
(function($){
var old_trim = $.trim;
function trim() {
switch (arguments.length) {
case 2:
throw new Error("Invalid argument." +
" $.trim must be called with either a string" +
" or haystack, replacer, replacement");
break;
case 3:
return arguments[0].replace(arguments[1], arguments[2]);
default:
return old_trim.call($, arguments);
}
}
$.trim = trim;
})(jQuery);
This pattern is sometimes called Duck Punching.
var trimmed = "test3, \t\r\n".replace(/[\s,]+$/, "");
This is exactly what regular expressions are good for.

Categories

Resources