0

I read many questions about removing characters from a string. But none of them resolved my issue.

I have this string:

"\"iconCls\":X.net.RM.getIcon(\"BulletWhite\")" 

I want to replace this part:

"X.net.RM.getIcon(\"BulletWhite\")" 

By this (double quotes in fact):

"\"\"" 

I use this code:

let dataString = "\"iconCls\":X.net.RM.getIcon(\"BulletWhite\")" let newString = dataString?.replacingOccurrences(of: "X.net.RM.getIcon(\"BulletWhite\")" as String, with: "", options: .regularExpression, range: nil) 

But it doesn't work. I can replace all characters until I want to replace strings containing parentheses.Any idea? Thanks!

2 Answers 2

3

You are passing the .regularExpression option but you are not actually using a regular expression.

Change:

.regularExpression 

to:

[] 

This gives the result you want:

let dataString = "\"iconCls\":X.net.RM.getIcon(\"BulletWhite\")" let newString = dataString.replacingOccurrences(of: "X.net.RM.getIcon(\"BulletWhite\")" as String, with: "", options: [], range: nil) 

Output:

"icnCls":

Even simpler:

let newString = dataString.replacingOccurrences(of: "X.net.RM.getIcon(\"BulletWhite\")" as String, with: "") 
Sign up to request clarification or add additional context in comments.

Comments

1

You don't need to use options or range for this.

let str = "\"iconCls\":X.net.RM.getIcon(\"BulletWhite\")" let replace = "X.net.RM.getIcon(\"BulletWhite\")" let replaceBy = "\"\"" let newString = str.replacingOccurrences(of: replace, with: replaceBy) 

4 Comments

But how can I convert it to remove backslash before double quotes? Is this an encoding format?
@greenpoisononeTV There are no backslashes in the actual string. There's nothing to remove.
@rmaddy Of course there are backslashes before all double quotes when I print the string.
@greenpoisononeTV That's just Xcode's debug output. If you put that string in a label, for example, there would be no backslashes. To be clear, I am referring to the values in the code posted in your question and the answers.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.