Link to home
Start Free TrialLog in
Avatar of aristanoble
aristanoble

asked on

Javascript equivalent for this php function

Can you write a javascript or jquery method that would accomplish the exact same function as this php method please?

    var $wordSeparator = '-';

    private function getStringAsNiceName($string) {
		//strip tags, trim, and lowercase
		$string = strtolower(trim(strip_tags($string)));
		//replace single quotes and double quotes first
		$string = preg_replace('/[\']/i', '', $string);
		$string = preg_replace('/["]/i', '', $string);

		$string = preg_replace('/&/', 'and', $string);

		//remove non-valid characters
		$string = preg_replace('/[^-a-z0-9]/i', $this->wordSeparator, $string);
		$string = preg_replace('/-[-]*/i', $this->wordSeparator, $string);

		//remove from beginning and end
		$string = preg_replace('/' . $this->wordSeparator . '$/i', '', $string);
		$string = preg_replace('/^' . $this->wordSeparator . '/i', '', $string);

		return $string;

Open in new window


This is a method I use in order to convert strings into URL friendly strings.
Avatar of Dave Baldwin
Dave Baldwin
Flag of United States of America image

http://phpjs.org/ may help, it is a resource that offers community-built JavaScript alternatives to PHP functions.
Avatar of aristanoble
aristanoble

ASKER

Thank you but I need this particular custom function converted because I use it on the server so I need the same result to appear on the client when I want to show a preview of the final url.
Try to use string.replace(new RegExp('oldString', 'gi'), "newString"); for punctual replacement and the JS trim function (see http://www.w3schools.com/jsref/jsref_trim_string.asp).
Thanks but my regex coding isn't very strong that's why I wanted to rely on an expert. From what I can tell your solution only achieves part of the goal. Can you provide an efficient snippet of javascript or jquery code that would return the same filtered string as the above php getStringAsNiceName function?
If you use the JS functions step by step, you should be able to replicate the php function.
I think it's more salient to you because of your experience but for me it doesn't seem that straight forward to just follow the JS functions step by step and I'll confidently and precisely replicate the php function and it's regular expressions. I would really prefer an expert to whip up an efficient snippet that I can trust with confidence; unless I'm asking for too much.
greetings  aristanoble, you have several many things in your PHP code that are not a known spec (value) like -
$this->wordSeparator

it may can help (at least for me)  if you give in plain Talk what exactly you need for -
//remove non-valid characters
      you have TWO preg_replace( ) for this, and I would think you could do it with ONE replacement, if you can better define the output from this as it appears to allow the alphabet, the numbers 0 to 9, but I am not sure about the second  preg_replace( )  with a - spec, , , as I said there is the $this->wordSeparator in these, is this a FIXED value like a space character or a variable thing, depending on other settings?

also not sure about the -
//remove from beginning and end
as a preg_replace( ) , seems like the php trim thing already did this?
do you know, and can you tell us exactly what needs to be = //remove from beginning and end
Well it's actually part of a class. $this->wordSeparator is calling the $wordSeparator property declared as "var $wordSeparator = '-';". It basically allows me to take any string and make it URL friendly. My objective is to use this method on the server but to show a preview on the client side using javascript. The preview must match the expected return on the server so the JS function must escape, format and filter the same as the php method. (Of course, I could make an ajax call to the server but I see no reason why I couldn't just do this in javascript client side)

<?php

class prettyName {

    var $wordSeparator = '-';

    public function getStringAsNiceName($string) {
		//strip tags, trim, and lowercase
		$string = strtolower(trim(strip_tags($string)));
		//replace single quotes and double quotes first
		$string = preg_replace('/[\']/i', '', $string);
		$string = preg_replace('/["]/i', '', $string);

		$string = preg_replace('/&/', 'and', $string);

		//remove non-valid characters
		$string = preg_replace('/[^-a-z0-9]/i', $this->wordSeparator, $string);
		$string = preg_replace('/-[-]*/i', $this->wordSeparator, $string);

		//remove from beginning and end
		$string = preg_replace('/' . $this->wordSeparator . '$/i', '', $string);
		$string = preg_replace('/^' . $this->wordSeparator . '/i', '', $string);

		return $string;
        }
}
?>

$prettyName = new prettyName();
$name = $prettyName->getStringAsNiceName('hello world'); //e.g. returns "hello-world",

Open in new window

yes I already know that this is in a CLASS declaration , and thanks for saying that the value for $this->wordSeparator is "-"

and I take it that this class is not something that you wrote, so you can not tell me about what is the functioning of the -
//remove non-valid characters
preg_replace( ) things.

OK, I really do not have the time now to do BOTH, as in write some javascript and then have to put your class in a PHP page and then run a hundred of different strings with different characters and <b> html tags and " and ' and other, to see if the getStringAsNiceName( ) and my JS will deliver the same output. Sorry about that. . .
Oh that sounds like overkill and more than what I'm asking for. I had assumed using the comments as guides and using similar if not the same reg expressions your final JavaScript function would then yield the same output. No?
As said before, I suggest you to take a look to the complete JS string reference at http://w3schools.com/jsref/jsref_obj_string.asp
Ok, I will thank you. But as for answering my question so that I can award points and close the question, are you saying that an expert couldn't use similar, if not the same, regex patterns and the comments as their guide in order to produce a good javascript equivalent? Please let me know and I'll close this question as being unanswerable. Or maybe assign the points to myself :)

Just to clarify, I'm assuming these comments:
//strip tags, trim, and lowercase
//replace single quotes and double quotes first
//remove non-valid characters
//remove from beginning and end
and these patterns:
/[\']/i
/["]/i
/&/
/[^-a-z0-9]/i
/-[-]*/i
/' . $this->wordSeparator . '$/i
/^' . $this->wordSeparator . '/i
should be able to assist any expert that knows javascript and has strong regex abilities to create a javascript function that returns url friendly strings of text.

One could even treat this as if I had never spoke of a php function and simply requested that an expert would take these comments and patterns as a guide to produce such a function.
The regular expression function allows you to define both criteria and type of characters you want to replace inside the string (for example /i for case-insensitive matching, /[^-a-z0-9]/ for any characters and digits).
Thank you Sar, that was helpful. Once an expert replies to my question with a javascript function that meets the objective; I'll award the necessary points and close it out.
@ aristanoble, , You seem to think that this is a simple thing, and yet you have not posted any Trial javascript function that you wrote, so we can advise you on how to make it work better. NO one else has posted any javascript to do the task, so maybe it anit so easy. Although the separate lines of code going preg_replace( ) in the PHP method are not individually difficult as a RegExpression, BUT the combined changing of the string with all of the 10 different string parses can be difficult to know if the final string in javascript will match the final string in the PHP, just by lookin at the PHP and javascript function code, as I tried to say to you, it takes time and effort to run may different strings through the PHP and JS to see if they all match, and then do experiments to get the JS output to match.
If you just want a javascript function that has NOT been tested against the PHP function, then here is my screwball attempt -
function makeURL(inStr){
inStr= inStr.trim(inStr);
inStr= inStr.toLowerCase(inStr);
inStr = inStr.replace(/<\/?[^>]+(>|$)/g, "");
inStr = inStr.replace("'", "");
inStr = inStr.replace('"', "");
inStr = inStr.replace(/[^\-a-z0-9]/g, "-");
inStr = inStr.replace(/-{2,}/g, "-");
inStr = inStr.replace(/^-/, "");
inStr = inStr.replace(/-$/, "");
return inStr;
}

Open in new window

I DID NOT TEST this JS against any thing of your PHP method, it's just a guess at what I think the PHP does.

I have this -
inStr = inStr.replace(/<\/?[^>]+(>|$)/g, "");
for the PHP strip_tags( ) however I know from using the strip_tags( ) that the function uses a much more significant string parse to remove tags than the simplistic  /<\/?[^>]+(>|$)/g   BUT as long as the HTML tags are properly formed then this javascript should work OK, but if there are tags without closing or tags within tags, then they will NOT match.
You do not seem to have any skill with javascript, ask questions if you need more help wid JS
ASKER CERTIFIED SOLUTION
Avatar of aristanoble
aristanoble

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
I tested as such -

var strInput = "#<h2>About \"is' 5&p+ </h2> <p>M*******<a href=\"/about\">Re-ad more</a></p>%";
var noTags = makeURL(strInput);
document.getElementById("dv0").innerHTML = "NO TAGS= "+noTags;

it returns -
about-is-5-p-m-re-ad-more

++++++

you should at least try my function, it does the job , as far as I can tell, you need to spend your own time, comparing the results for the JS and your PHP for different strings, but if your converted strings are as simple as you only example "Hello World" then it'll work
Based on the expert's suggestions, screwball attempt, and my "lack of ANY skill in javascript" this question was deemed unanswerable, untestable, and couldn't produce the php equivalent result I was looking for. I'll come up with the solution on my own.