Javascript strip functions

Coding Critique is the place to post source code for peer review by other members of DevNetwork. Any kind of code can be posted. Code posted does not have to be limited to PHP. All members are invited to contribute constructive criticism with the goal of improving the code. Posted code should include some background information about it and what areas you specifically would like help with.

Popular code excerpts may be moved to "Code Snippets" by the moderators.

Moderator: General Moderators

Post Reply
tores
Forum Contributor
Posts: 120
Joined: Fri Jun 18, 2004 3:04 am

Javascript strip functions

Post by tores »

feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


These functions strip away any whitespace from the beginning and end of the input string... The first tries to be fast, the second uses regex. Haven't really tested the speed of the two, though.

[syntax="javascript"]
function strip(str) {

	if (typeof str != 'string') {
		return;
	}
	
	var s = 0, e = str.length-1;
	var ss = 0, es = 0;
	var c = '';
	
	// Look for whitespace from start and end of string
	for (var i = 0, j = e, m = str.length/2; i < m; i++, j--) {
		
		c = str[i];
		if (ss == 0 && (c == ' ' || c == '\t' || c == '\n')) {
			s++;
		} else {
			ss = 1;
		}

		c = str[j];
		if (es == 0 && (c == ' ' || c == '\t' || c == '\n')) {
			e--;
		} else {
			es = 1;
		}
	}
	
	// Include centermost char if it's not a whitespace		
	if (str.length % 2) {
		c = str[m+1];
		if (c == ' ' || c == '\t' || c == '\n') {
			s++;
		}
	}
	
	c = str.substring(s, e+1);
	
	// If the input string contains only whitespace we still have a single whitespace
	if (c == ' ' || c == '\t' || c == '\n') {
		c = '';
	}
	
	return  c;
}

function strip2(str) {

	if (typeof str != 'string') {
		return;
	}
	
	return str.replace(/^\W*/, '').replace(/\W*$/, '');
}
-tores


feyd | Please use[/syntax]

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]
User avatar
idevlin
Forum Commoner
Posts: 78
Joined: Tue Jun 26, 2007 1:10 pm
Location: Cambridge, UK

Post by idevlin »

Why don't you just use trim()?

Or do you have some reason which you've not explained for not using this?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Is there something in particular you want us to critique in this snippet?
tores
Forum Contributor
Posts: 120
Joined: Fri Jun 18, 2004 3:04 am

Post by tores »

1. This is client-side. Like, if you want to strip a form input field, before validating it client-side.
2. Didn't know whether to post it directly in the snippets forum... Thought it could use some scrutiny before being an "official" code-snippet.
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

Doesn't this work?

Code: Select all

var str = " this needs trimming    ";
var trimmed = str.replace(/(^\s+)|(\s+$)/g, "");
EDIT | And mine would be fast since it just looks at start and end
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Users do not have write access to the snippet forum.

Both of the functions perform differing actions. The first doesn't catch all whitespace characters while the second catches more that just whitespace characters.

A Google search for "javascript trim" will turn up several examples of more straight-forward variants.
User avatar
idevlin
Forum Commoner
Posts: 78
Joined: Tue Jun 26, 2007 1:10 pm
Location: Cambridge, UK

Post by idevlin »

tores wrote:1. This is client-side. Like, if you want to strip a form input field, before validating it client-side.
2. Didn't know whether to post it directly in the snippets forum... Thought it could use some scrutiny before being an "official" code-snippet.
Yeah sorry, for some bizarre reason my brain omitted the word JavaScript in your initial post :oops:
tores
Forum Contributor
Posts: 120
Joined: Fri Jun 18, 2004 3:04 am

Post by tores »

googled for javascript strip... Wasn't many good candidates returned by that search...

Anyways... the regex was faulty, and the other function didn't strip \r \v or formfeed...

So... thanks for the feedback.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

I said "trim" because that's what this type of functionality is typically called, especially in PHP.

The first link in "Javascript trim" provides: http://www.somacon.com/p355.php, which is a fairly good implementation.
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

Extending on feyd's link, which basically demonstrates the same as I did, PHP allows you to list characters to trim.

Code: Select all

String.prototype.trim = function(charlist)
{
  if (charlist)
  {
    //This probably needs refining
    charlist = charlist.replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, "\\$1");
  }
  charlist = charlist || "\\s";
  var re = new RegExp("^[" + charlist + "]+|[" + charlist + "]+$", "g");
  return this.replace(re, "");
};

Code: Select all

var str = "xxstring herexx";
var trimmed = str.trim("x");
saul11
Forum Newbie
Posts: 1
Joined: Wed Jul 11, 2007 5:56 am

Post by saul11 »

Nice code, it's a pitty that you're not sure if it needs some refinement.
Post Reply