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?
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.
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.
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(' ') .
string.replace(/-/g,' ');
Will replace any occurences of -
with in the string
string
.
You would use String's replace
method:
statelookup = statelookup.replace(/-/g, ' ');
API Reference here.
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