Definition
SPSS REPLACE replaces a substring in a string by a different (possibly empty) substring.
SPSS Replace – Removing Spaces
URLs 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 REPLACE.
SPSS Replace Syntax Example 1
data list free/title(a50).
begin data
“Suffix All Variable Names”
“SPSS Syntax – Six Reasons you Should Use it”
“Reverse Code Variables with Value Labels”
end data.*2. Declare new string variable for URL.
string url(a50).*3. URL is title with spaces removed.
compute url = replace(title,’ ‘,”).
exe.
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. - Note that this creates a new problem: URLs for titles that contain “
-” now have triple dashes. However, we can simply useREPLACEagain 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),’ ‘,’-‘).
exe.*5. Replace triple dashes by single dashes.
compute url = replace(url,’—‘,’-‘).
exe.*6. Convert URL to lowercase.
compute url = lower(url).
exe.
*7. Delete values from URL.
compute url = ”.
exe.
*8. Compute URL in one go.
compute url = lower(replace(replace(rtrim(title),’ ‘,’-‘),’—‘,’-‘)).
exe.
