0

I have this text :

He's a self made man who gets what he wants.

The small blue forget me not flower was first used by the Grand Lodge.

And this function:

function MyFunction() let myList1 = ["self made man", "gorget me not"] for elem in MyList1 if search("=/elem", 'W') == 0 echo "I want to replace space by hyphen between this three words" ---> CODE endif endfor endfunction 

I want to get this text after executing the function :

He's a self-made-man who gets what he wants.

The small blue forget-me-not flower was first used by the Grand Lodge.

Can you help me to write the missing line (---> CODE) ?

2 Answers 2

1

You're looking for the substitute() function...

substitute({expr}, {pat}, {sub}, {flags}) 
  • expr is the string to work on
  • pat is the pattern similar to :s/pat/sub/g.
  • sub is the substitution similar to sub in the same :s command.
  • flags, should include "g" as in global (again, like :s)

So...

let elem = substitute(elem, ' ', '-', 'g') 

The second param could also be '\s' indicating a single whitespace char.

-1

Here's my function (based on @BLayer’s answer:

He's a self made man who gets what he wants. The small blue forget me not flower was first used by the Grand Lodge.

function MyFunction() let myList1 = ["self made man", "forget me not"] for elem1 in myList1 if search("=/elem1", 'W') == 0 let elem2 = substitute(elem1, ' ', '-', 'g') exe '%s/'elem1.'/'elem2 endif endfor endfunction 

He's a self-made-man who gets what he wants. The small blue forget-me-not flower was first used by the Grand Lodge.

2
  • 1
    If you want to say thanks, an upvote is a good start! You should accept the answer that solved your problem. Commented Mar 24, 2020 at 13:06
  • 1
    Thanks DBK. Arsene you're relatively new here so this would be worth reading: vi.stackexchange.com/help/someone-answers. I notice for the four questions you've asked that have received responses you haven't accepted (nor, perhaps, voted) on any of the answers. It's a good idea to say "thanks" (with votes/accepts) to people that have taken time out of their day to help you. Cheers. (Oh, also, it's not necessary/advisable to add an answer that basically is another answer plugged into your code.) Commented Mar 25, 2020 at 0:58

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.