How to Check given string is in HTML format or not in swift

In one scenario I need to check whether api response is in HTML format or in JSON format. For that first I am converting data to string and checking is it in HTML format or not?. Is there any Regex available to check string is html string or not? or is there any another way available?.


Solution 1:

Check a string is a HTML string:

func isValidHtmlString(_ value: String) -> Bool {
    if value.isEmpty {
        return false
    }
    return (value.range(of: "<(\"[^\"]*\"|'[^']*'|[^'\">])*>", options: .regularExpression) != nil)
}

let testString = "<p> test html string </p>"
print("\(isValidHtmlString(testString))")

Reference: https://www.geeksforgeeks.org/how-to-validate-html-tag-using-regular-expression/

Check a string is a JSON string:

let jsonString = "{}"
if JSONSerialization.isValidJSONObject(jsonString.data(using: .utf8)!) {
        print("valid")
} else {
        print("invalid")
}