If I have a string with multiple spaces between words:
Be an excellent person
using JavaScript/regex, how do I remove extraneous internal spaces so that it becomes:
Be an excellent person
You can use the regex /\\s{2,}/g
:
var s = "Be an excellent person"
s.replace(/\s{2,}/g, ' ');
This regex should solve the problem:
var t = 'Be an excellent person';
t.replace(/ {2,}/g, ' ');
// Output: "Be an excellent person"
Something like this should be able to do it.
var text = 'Be an excellent person';
alert(text.replace(/\s\s+/g, ' '));
you can remove double spaces with the following :
var text = 'Be an excellent person';
alert(text.replace(/\s\s+/g, ' '));
Snippet:
var text = 'Be an excellent person'; //Split the string by spaces and convert into array text = text.split(" "); // Remove the empty elements from the array text = text.filter(function(item){return item;}); // Join the array with delimeter space text = text.join(" "); // Final result testing alert(text);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.