Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript replace a character with a space

Tags:

javascript

I need to get the name of the page from a url. I did this way:

var filename = window.location.href.substr(window.location.href.lastIndexOf('/')+1)
// -> 'state.aspx' 

var statelookup = filename.substr(0, filename.lastIndexOf('.'))
// -> 'state'

Now for e.g, my statelookup has a value like New-York or North-Carolina, how do I replace hyphen with a space in between?

like image 374
user407079 Avatar asked Aug 08 '11 17:08

user407079


People also ask

How do you replace a space in JavaScript?

Use the String. replace() method to replace all spaces in a string, e.g. str. replace(/ /g, '+'); . The replace() method will return a new string with all spaces replaced by the provided replacement.

How do you replace all underscore with space in JavaScript?

To replace the underscores with spaces in a string, call the replaceAll() method, passing it an underscore and space as parameters, e.g. str. replaceAll('_', ' ') . The replaceAll method will return a new string where each underscores is replaced by a space.

How do you put spaces between letters in JavaScript?

To add a space between the characters of a string, call the split() method on the string to get an array of characters, and call the join() method on the array to join the substrings with a space separator, e.g. str. split(''). join(' ') .


2 Answers

string.replace(/-/g,' ');

Will replace any occurences of - with in the string string.

like image 85
Madara's Ghost Avatar answered Nov 01 '22 15:11

Madara's Ghost


You would use String's replace method:

statelookup = statelookup.replace(/-/g, ' ');

API Reference here.

like image 44
FishBasketGordo Avatar answered Nov 01 '22 15:11

FishBasketGordo