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
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.
We can use the the aforementioned replace() method to target spaces and replace them with underscores. It looks like this: str = str. replace(" ", "_");
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.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With