Link to home
Start Free TrialLog in
Avatar of mnb93
mnb93

asked on

preg_match preg_replace in javascript.

Basically I would like to know how to do these PHP things:

preg_match preg_replace

and

                        $x = str_split($x, 1);
                        $x = array_unique($x);
                        $x = implode('',$x);

in javascript.
ASKER CERTIFIED SOLUTION
Avatar of Ivo Stoykov
Ivo Stoykov
Flag of Bulgaria image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of mnb93
mnb93

ASKER

What about: preg_match preg_replace?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
var x = "This is a sentence";
x.replace("is","was");

if(x.indexOf("sentence") != -1)
{
alert("We found a match");
}
BTW, an alternative for "preg_match" would be

/RegExp/.exec ("string");

This does the same thing as "string".match ( /RegExp/ );
Avatar of mnb93

ASKER

var x = "some_long_string";
x = x.split('_', 1);

But $x = str_split($x, 1);

Means to put each char into an array.
Avatar of mnb93

ASKER

v.match (/^\s|\s$/)
doesn't work.
Avatar of mnb93

ASKER

I wanted to use it in an if?
Avatar of mnb93

ASKER

eg.

    if(v.match ('/^\s|\s$/'))
    {
//
}
Avatar of mnb93

ASKER

well without the '
Avatar of mnb93

ASKER

And for this: /[^A-Za-z0-9\'"|_\[\]\- ]/ where I am escaping the ' do I need to do that?
Avatar of mnb93

ASKER

Ok I am all good except:

var x = "some_long_string";
x = x.split('_', 1);

But $x = str_split($x, 1);

Means to put each char into an array.
1)

    if( /^\s|\s$/.test(v)  ) {
 ...
    }


There should be no 'quotes' around the slashes (/ ... /). In JS regular expressions are native objects so you don't need to quote them around '...'.

2)

You do not need to escape the ', because it isn't special in RegExp.

/[^A-Za-z0-9'"|_\[\]\- ]/

3)

Use
x = x.split ( /\B|\b/ );
Avatar of mnb93

ASKER

array_unique has no equivalent you could use sort and the remove second appearanve of a data
i/e/

a = new Array("X" ,"y" ,"d", "Z", "v","m","r");
a = a.sort();
then use for(...) to compare....

How do I compare it?
Avatar of mnb93

ASKER

function array_unique(arr) {
    var newArray = [];
    var existingItems = {};
    var prefix = String(Math.random() * 9e9);
    for (var ii = 0; ii < arr.length; ++ii) {
        if (!existingItems[prefix + arr[ii]]) {
            newArray.push(arr[ii]);
            existingItems[prefix + arr[ii]] = true;
        }
    }
    return newArray;
}