-2

I get a input from uitextfield box. i can replace quotes("'") to empty(""). using

textfield.text.replacingOccurrences(of: "'", with: "") 

is not working

textfield.text = "name's"
let trim = textfield.text?.replacingOccurrences(of: "'", with: "")

expected OUTPUT:

names

actual OUTPUT:

name's

mag_zbc
  • 6,801
  • 14
  • 40
  • 62
Raj Kumar
  • 1
  • 8
  • 1
    `textfield.text = "name's" let trim = textfield.text?.replacingOccurrences(of: "\'", with: "")` try that – Vollan Jul 26 '19 at 13:31
  • 3
    Post the _actual_ code/input... the snippet you have posted in your question already produces your expected output. – Alladinian Jul 26 '19 at 13:36
  • Where do you have the `replacingOccurrences` code? – RajeshKumar R Jul 26 '19 at 13:38
  • 2
    My guess: The text field does not contain an apostrophe (`'`) but a single left quotation mark (`‘`) – Martin R Jul 26 '19 at 13:40
  • Use https://stackoverflow.com/a/28503676/4757272 this regex to clean from all wierd characters. – Vollan Jul 26 '19 at 13:44
  • As other people said, the first quote may actually be one of those _pesky_ smart quotes, rather than a straight quote. And with out more code, I’m thinking maybe you aren’t replacing the textfield’s text, or printing the right value (we need a bit more context). Make sure you do a `print(trim)` or if you’re trying to replace the textfield, `textfield.text=trim` – Matt Bart Jul 26 '19 at 15:25
  • thanks. i can get the solution it contain smartquotes.smartquotes set to No its working. Textfield.smartQuotesType = .no – Raj Kumar Jul 29 '19 at 06:56

1 Answers1

0

text.replacingOccurrences can be used with regular expressions so using the group ['`´] could work here (I am not aware of any meta character for this). As @Rob mentioned in the comments it might be worth expanding the pattern further like [‘’'`´] or [‘’‛'′´`❛❜] or use "\p{Quotation_Mark}"

let trim = text.replacingOccurrences(of: "['`´]", with: "", options: .regularExpression)

It doesn't replace è or é which is good I suppose

let text = "name's are Josè and André, strings are `abc` and ´def´"
let trim = text.replacingOccurrences(of: "['`´]", with: "", options: .regularExpression)

print(trim)

yields

names are Josè and André, strings are abc and def

Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
  • 1
    Maybe `[‘’'\`´]` or `[‘’‛'′´\`❛❜]` – Rob Jul 26 '19 at 16:29
  • 1
    Or, if you’re willing to throw double quotes under the bus, `text.replacingOccurrences(of: #"\p{Quotation_Mark}"#, with: "", options: .regularExpression)`. – Rob Jul 26 '19 at 16:35