Solved

Convert PHP preg_replace code to JavaScript replace

Posted on 2011-02-21
1
494 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
Comment Utility

//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

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

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…
JavaScript can be used in a browser to change parts of a webpage dynamically. It begins with the following pattern: If condition W is true, do thing X to target Y after event Z. Below are some tips and tricks to help you get started with JavaScript …
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)
The viewer will learn the basics of jQuery including how to code hide show and toggles. 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…

762 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

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now