Skip to main content
  1. About
  2. For Teams
Asked
Viewed 29k times
25

I have a string var string = "my__st_ri_ng". I want to replace all underscores with single space and I want to store it it another variable. Each underscore should have a space replacement, which means multiple consecutive underscores should have respective number of empty spaces. I want to get my mentioned variable as my<sp><sp>st<sp>ri<sp>ng. How can I do this using jquery??

Thanks in advance...:)

blasteralfred

4 Answers 4

45

What you need is Javascript's replace function.

var str1 = "my__st_ri_ng";
var str2 = str1.replace(/_/g, ' ');

You do not need jQuery at all for this task...

Sign up to request clarification or add additional context in comments.

5 Comments

replaces only first underscore
Yeah, was already on it :). Should not be so drunk in the morning.
Also.. you not necessarily need RegEx :)
Please also note that you don't include quotes around the regex. I made that mistake: str1.replace(/_/g, ' ') is correct but str1.replace("/_/g", ' ') isn't...
@Tom Well, it is correct, but does something absolutely different indeed :)
8

To replace all occurrences of _, use a regular expression with the g (global) flag.

"my__st_ri_ng".replace(/_/g, " "); // "my  st ri ng"

6 Comments

But he wants to do it in jQuery! :) +1 for having the correct answer of these 3
you know I'll never hesitate to write a jQuery plugin for this with full-on documentation.
@Anurag: Looking forward to the plugin. Vanilla javascript is so boring! $(this).stringReplace({search:'my_string', replace: ' ', replaceAll : true}) is much more exciting!
@bazmegakapa - thanks :) .. @Madmartigan - haha, very nice draft.. Now all I need are the use cases, a requirements doc, a design doc, functional specs. Oh, and test cases too :)
@bazmegakapa - I can smell a new startup out of this plugin :P
|
2

Try this...

var oldStr = 'I_told_you';

var newStr = oldStr.split('_').join(' ');

Comments

0

You don't need jQuery or even RegEx, just simple JavaSript:

var newStr = oldStr.replace('_', ' ');

2 Comments

Will only replace the first one.
@bazmegakapa Hmm.. really? I'm gonna check it out.

Your Answer

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.

Morty Proxy This is a proxified and sanitized view of the page, visit original site.