Solved

Convert PHP preg_replace code to JavaScript replace

Posted on 2011-02-21
1
509 Views
Last Modified: 2012-05-11
I would like this PHP REGEX to be converted to JavaScript.

I only want the extra whitespace to be replaced with a newline if the whitespace already contains a newline.

If extra whitespace does NOT contain a newline then the extra whitespace should be replaced with a space.

It works correctly in PHP but I need it converted to JavaScript.

Thanks!
<pre><?php

$xyz='Hello,     world.
This      is	 at test
               and only a          test';
echo preg_replace("/(?=\s\s)\s*?(\n)\s*|(\s)\s+/", "$1$2", $xyz);

?></pre>

<script type="text/javascript">

var xyz = 'Hello,     world. \n This      is	 at test\n               and only a          test';
alert(xyz); // Should replace extra whitespace with 1 space or 1 new line if it contains new line

</script>

Open in new window

0
Comment
Question by:hankknight
1 Comment
 
LVL 20

Accepted Solution

by:
Proculopsis earned 500 total points
ID: 34944200

//is this any good:

var xyz = 'Hello,     world. \n This      is       at test\n               and only a          test';

xyz = xyz.replace( /[ \t]*\n[ \t]*\n/g, "\n" );
xyz = xyz.replace( /[ \t]+/g, " " );

alert(xyz); // Should replace extra whitespace with 1 space or 1 new line if it contains new line
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article shows how to create and access 2-dimensional arrays in JavaScript.  It includes a tutorial in case you are just trying to "get your head wrapped around" the concept and we'll also look at some useful tips for more advanced programmers. …
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

685 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question