Doing a function that takes a as an argument str
, returns la str
with the spaces changed to hyphens:
function urlSlug(title) {
str = title.toLowerCase();
arr = str.split(" ");
definitivestr = arr.join("-");
return definitivestr
}
For example urlSlug("Winter Is Coming")
it should return " winter-is-coming
"
The particularity is that, for example, if urlSlug(" Winter Is Coming")
the function is given, it no longer returns " winter-is-coming
" but " -winter-is--coming
".
For which I have added this:
function urlSlug(title) {
str = title.toLowerCase();
arr = str.split(" ");
for (var i = 0; i < arr.length; i++){if (arr[i] == ""){arr.splice(i,1)}}
definitivestr = arr.join("-");
return definitivestr
}
However it is still not valid, because if it is given again urlSlug(" Winter Is Coming")
the function still does not return " winter-is-coming
" but " winter-is- coming
".
So it hasn't occurred to me if you can put in the if statement
other one if
to look if the " arr[i]
" has /\W/
to delete everything/\W/
function urlSlug(title) {
str = title.toLowerCase();
arr = str.split(" ");
for (var i = 0; i < arr.length; i++){if (arr[i] == ""){arr.splice(i,1)}
if ((newnewstr[i]) == /\W/){newnewstr.splice(i,1)}}
definitivestr = arr.join("-");
return definitivestr
}
Now this last one is wrong because I don't know how to integrate aRegex
In Javascript you have String.prototype.replace() to replace characters in strings, and it accepts regular expressions. A valid solution for your case is:
Explanation:
trim()
we remove spaces at the beginning and at the end.\s
search any space+
means one or more occurrencesg
means "global": if you don't use it, it will stop when it finds the first space (you can check it yourself)And to check if a regular expression is found in a string you have RegExp.prototype.test() . The
if ((newnewstr[i]) == /\W/)
, as you've put it, just does a value comparison, and they clearly don't match becausenewnewstr[i]
it's a string and/\W/
it's a regular expression.In the end with regular expressions it takes a lot of practice until you find the one that suits your needs.