REPLACE replaces a substring in a string by a different (possibly empty) substring.
SPSS Replace - Removing SpacesURLs are created from "title" by using REPLACE. The syntax below demonstrates how to do this.
We have a dataset holding the titles of web pages and we'd like to convert these to URLs. For one thing, we don't like spaces in URLs. The syntax below shows how to remove them. Step 1 creates a tiny dataset (just run and otherwise ignore it) and step 3 demonstrates how to remove spaces using
SPSS Replace Syntax Example 1
data list free/title(a50).
"Suffix All Variable Names"
"SPSS Syntax - Six Reasons you Should Use it"
"Reverse Code Variables with Value Labels"
*2. Declare new string variable for URL.
*3. URL is title with spaces removed.
compute url = replace(title,' ','').
SPSS Replace - Replacing Spaces
- Removing all spaces from our titles doesn't make our URLs very readable. We'll therefore replace all spaces in
titleby dashes. Note that this may require RTRIM so we added that in step 4 below.Precisely,
RTRIMis applied automatically in Unicode mode so in that case it may be omitted. However, we recommend using it anyway to stay on the safe side.
- Note that this creates a new problem: URLs for titles that contain "
-" now have triple dashes. However, we can simply use
REPLACEagain for correcting these.
- In practice, we usually like our URLs in lowercase only. After doing so in step 6, our URLs are as desired.
- Using consecutive string modifications for arriving at the desired result as done here is perfectly fine. Job done. However, do realize that functions can be used within functions (referred to as substitution). This makes it possible to run all we've done so far in a single line. Steps 7 and 8 first erase
URLand then reconstruct it in one go.
SPSS Replace Syntax Example 2
compute url = replace(rtrim(title),' ','-').
*5. Replace triple dashes by single dashes.
compute url = replace(url,'---','-').
*6. Convert URL to lowercase.
compute url = lower(url).
*7. Delete values from URL.
compute url = ''.
*8. Compute URL in one go.
compute url = lower(replace(replace(rtrim(title),' ','-'),'---','-')).