Striping spaces from the beginning and end of a string through RegExp

R

romayankin

I'm trying to create PHP trim() function equivalent using pure JS code
that truncates spaces from the begging and from the end of the given
string. One of the solutions is to use two "while" loops that will run
through the chars from the beginning and then on the end and cut
spaces. Instead I want to write a RegExp to accomplish this. Here is
the sample to give you an idea of my problem:

var str = new String(" and; n4m ")
var patternTrim = /(^\s+)(.*)(\s+$)/;
var arr = str.match(patternTrim);

Note the space char in the middle of the evaluated string. The
resulting string i want to have looks like this "and; n4m"
 
R

Rob Williscroft

wrote in in
comp.lang.javascript:
I'm trying to create PHP trim() function equivalent using pure JS code
that truncates spaces from the begging and from the end of the given
string. One of the solutions is to use two "while" loops that will run
through the chars from the beginning and then on the end and cut
spaces. Instead I want to write a RegExp to accomplish this. Here is
the sample to give you an idea of my problem:

var str = new String(" and; n4m ")
var patternTrim = /(^\s+)(.*)(\s+$)/;
var arr = str.match(patternTrim);

Note the space char in the middle of the evaluated string. The
resulting string i want to have looks like this "and; n4m"

The trick is to match waht you want to remove (not the whole
string) and then use .replace():

function trim( s )
{
return s.replace( /^\s+|\s+$/g , "" );
}

HTH.

Rob.
 
D

Douglas Crockford

I'm trying to create PHP trim() function equivalent using pure JS code
that truncates spaces from the begging and from the end of the given
string. One of the solutions is to use two "while" loops that will run
through the chars from the beginning and then on the end and cut
spaces. Instead I want to write a RegExp to accomplish this. Here is
the sample to give you an idea of my problem:

var str = new String(" and; n4m ")
var patternTrim = /(^\s+)(.*)(\s+$)/;
var arr = str.match(patternTrim);

Note the space char in the middle of the evaluated string. The
resulting string i want to have looks like this "and; n4m"

First, do not use new String in JavaScript. It doesn't do what you expect. Use
use string literals.

String.prototype.trim = function () {
return this.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
});

var str = " and; n4m ";
var arr = str.trim();

http://javascript.crockford.com/remedial.html
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,906
Latest member
SkinfixSkintag

Latest Threads

Top