2

In the string

somethingcryptic12A@#$~` abc def@#

, I would like to replace the first word by new so that it would then be new

new abc def@#

. How can I do this using regular expression. I have made the first word cryptic to indicate that it can contain any character and any number of characters. It's the first word if there is a space after it.

1
  • In my defense, I was able to come up with the full solution after some initial help from Some1. I had tried some solutions like [a-zA-Z] but that wouldn't work for all scenarios. Commented Feb 1, 2013 at 19:29

1 Answer 1

9

You can use this regular expression

^\S+

^ represents start of the string

\S matches any character except space..

+ matches preceding character 1 to many times

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

3 Comments

correct solution is var newvalue = original.replace(/^\S+/g, 'new');
\S matches anything other than "whitespace characters", which is equivalent to [^ \f\n\r\t\v​\u00A0\u1680​\u180e\u2000​\u2001\u2002​\u2003\u2004​\u2005\u2006​\u2007\u2008​\u2009\u200a​\u2028\u2029​\u2028\u2029​\u202f\u205f​\u3000] in character class notation.
thanks Vishal - you should post your solution as an answer and I'll upvote it. You saved me five minutes. ta

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.