1

I have text and some words in text are with spaces like I like R O S E S and trees. Spaces are made with help of this function

this.text = this.text.replace(new RegExp(this.words.join('|'), 'g'), function insertSpaces(x) {
   return x.split('').join(' ');
 }); };

where text is I like roses and trees and word is ROSES, I would like to make it possible to click on the word R O S E S between letters and if I click there appears "-"instead of spaces. So, if I click between R and O there appears R-O S E S instead of R O S E S, if I click between O and S, appears R O-S E S instead of R O S E S and so on...is it possible with Angular2?

UPDATE

I try this code now

getCaretPos(oField: any, a: any) {
    if (oField.selectionStart || oField.selectionStart === '0') {
      this.caretPos = oField.selectionStart;

//assign char at choosed position to new variable
      a = this.text.charAt(this.caretPos);

//replace this char with "-"
      this.text.replace(a, '-');
    }
  }
}

2 Answers 2

1

This link demonstrates how to get the current caret position: http://blog.sodhanalibrary.com/2016/10/get-cursor-position-from-text-area.html#.WURW3GjythE

You could then change the text to insert the dash at that character position.

Does that sound like it would work for you?

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for the hint.. does it work just with textarea? Or is it possible to work with <p> as well?
And how can I insert the dash at that character position? Sorry, I am very beginner...just tried a replace() function, but doesn't work...must be something like oField.replace('-'); ?...
Update your question with the code you are trying for the replace.
0
getCaretPos(oField: any, a: any) {
    if (oField.selectionStart || oField.selectionStart === '0') {
      this.caretPos = oField.selectionStart;
      a = this.text.charAt(this.caretPos);
      alert(a);
      this.text = this.text.substring(0, this.caretPos) + '-' + this.text.substring(this.caretPos + 1);
    }
  }

Works for me, hope this will help somebody else)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.