i want to know is there any inbuild function to add spaces in javascript after particular interval..!!?

there is string '00009999' i want to add blank space 0000 9999 after every 4 digits.?

// add spaces after every 4 digits (make sure there's no trailing whitespace)
somestring.replace(/(\d{4})/g, '$1 ').replace(/(^\s+|\s+$)/,'')
// add spaces after every 4 digits (make sure there's no trailing whitespace)
somestring.replace(/(\d{4})/g, '$1 ').replace(/(^\s+|\s+$)/,'')

this script works only when the string is numeric not when it is aplhanumeric

anyways thanks for help

ohh i got it instead of d i have write 'w' to make it alphanumeric..!!

thanks buddy..!

can u explain this part..??

replace(/(^\s+|\s+$)/,'')

i will appreciate that..

That will remove any preceding or trailing white space from the string.

Also, you may want to phrase your initial question better :P You asked for a script to add a space 'after every 4 digits' which is what you got..
\w will match a-z, A-Z, 0-9 and underscores, so yes, replacing the d with a w should work if you want a space inserted after every 4 characters.

Thanks for the solution.

replace(/(^\s+|\s+$)/,'') seems not to take away preceding AND trailing white space at the same time.

When I tested it with Servoy/JavaScript, it took out only the leading white spaces and left the trailing inside.

Sorry for the belated response here, but is there a reason that the native JS trim() function couldn't be used on the string, after the regex already does its job of adding spaces in the middle?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.