Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace underscores in string

Tags:

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

like image 457
Alfred Avatar asked Apr 06 '11 07:04

Alfred


People also ask

How do I change underscore with spaces in Python?

replace() method to replace underscores with spaces, e.g. result = my_str. replace('_', ' ') . The str. replace() method will replace all occurrences of an underscore with a space in the string.

How do you change spaces to underscores?

We can use the the aforementioned replace() method to target spaces and replace them with underscores. It looks like this: str = str. replace(" ", "_");

How do I change a space in JavaScript?

The \s meta character in JavaScript regular expressions matches any whitespace character: spaces, tabs, newlines and Unicode spaces. And the g flag tells JavaScript to replace it multiple times. If you miss it, it will only replace the first occurrence of the white space.


1 Answers

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

like image 152
kapa Avatar answered Nov 03 '22 19:11

kapa