Farukh Zahoor Farukh Zahoor - 4 months ago 5
Javascript Question

How to add space with continuous long string

How to add space with continuously long string if there is no space in string after certain characters using JavaScript

For example string is


Helocsdnsajdnsajndjksandjks addwdwdwdnsajkkwfjnwkjqnf
wkjnfkjewnfefewfefewdd


and we want space after 10 characters

Result should be


Helocsdnsa jdnsajndjk sandjks addwdwdwdn sajkkwfjnw kjqnf wkjnfkjewn
fefewfefew dd

Answer

You can use /([^ ]{10})/g with .replace() method to add space after every 10 characters. Try this:

var str = "Helocsdnsajdnsajndjksandjks addwdwdwdnsajkkwfjnwkjqnf wkjnfkjewnfefewfefewdd";
str = str.replace(/([^ ]{10})/g, "$1 ");
console.log(str)