Solved

Convert PHP preg_replace code to JavaScript replace

Posted on 2011-02-21
1
501 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

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

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. …
The task A number given should be formatted for easy reading by separating digits into triads. Format must be made inline via JavaScript, i.e., frameworks / functions are not welcome. So let’s take a number like this “12345678.91¿ and format i…
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)

770 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