Table of Contents:-
The first argument is the pattern to be searched within the calling string to be replaced, and the second is the substitute.
Replace spaces with a dash in the string “Java Script”
let dummyString = "Java Script"; dummyString = dummyString.replace(/\s+/g, '-'); console.log(dummyString);
- Here in the above code replace() function is used. The Regular expression is /\s+/g
- /and / marks the beginning and end of a pattern.
- \s+ matches at least one space character within the string.
- g specifies to search all the occurrences of the pattern within the string.
- ‘-‘ is the replacement used to substitute the space.
Replace spaces with a dash(-) in the string “Java Script”
let dummyString = "Java Script"; dummyString = dummyString.split(/[\s]+/).join("-"); console.log(dummyString);
- The split() method is used to split the string into an array of elements. The division is based on spaces (\s)
- Note that the separator used in the split() method is a regular expression /[\s]+/ so that this solution will work even if there are multiple spaces.
- Finally, join all the array elements using the dash (‘-‘) with the help of the join(‘-‘) method separated by a single space to form a new string.