3

When inputting a string with a format:

the beginning r or R, then some non-digit letters, I want to replace the string with R.

It's in this situation:

onkeyup="this.value=this.value.replace(/^[rR]\D/g,'R')"

But it does not work.

Somebody can help me out? Thanks.

7
  • jsfiddle.net/arunpjohny/scakouae/1 ? Commented Aug 17, 2015 at 5:52
  • 1
    Post your possible inputs along with expected outputs Commented Aug 17, 2015 at 5:53
  • something like this this.value.replace(/^[^r^R]/g,'R')? Commented Aug 17, 2015 at 5:55
  • 1
    @ArunPJohny's jsfiddle does work for me (testing on Chrome). You don't even need the g modifier, since a regex which starts at ^ will match at most once (no multiple substitutions necessary). Commented Aug 17, 2015 at 6:11
  • 2
    /^/ never requires the g flag, how many "start of strings" are there? ;-) Commented Aug 17, 2015 at 6:15

1 Answer 1

2

Use the following regex:

     onkeyup="this.value=this.value.replace(/^[rR]\D+/, 'R')";

See this DEMO:

<input onkeyup="this.value=this.value.replace(/^[rR]\D+/,'R')" />

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

2 Comments

Thanks, chsdk. It's what I want. And @ArunPJohny 's answer also works fine. Thank all of you.
Great, glad it helps.

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.