1

I have been looking everywhere and can't find this..

I got a string and I want to replace the whole string with only the first word.

for example:

String: "hello world"

New String: "hello"

Thanks in advance!

Michael Low
  • 24,276
  • 16
  • 82
  • 119
GermanMan
  • 103
  • 1
  • 11

2 Answers2

6
var s = "hello world"
s = s.replace(/(\w+).*/,"$1");

that'll do it.

Joseph Marikle
  • 76,418
  • 17
  • 112
  • 129
  • Damn NICE! I gotta figure this out. Do you know a table where each of the symbols mean you used to create that? – GermanMan Oct 24 '11 at 18:55
  • 1
    @GermanMan [this site](http://www.regular-expressions.info/javascript.html) is a good resource – Joseph Marikle Oct 24 '11 at 18:58
  • This is working good.. But this doesen't work with other language words :-( – Anand Jun 23 '15 at 14:14
  • @Anand Interesting. Do you have an example you could share? As I understand it, `\w` should match non-whitespace characters. It shouldn't have a problem with other languages, but I could be completely wrong there. – Joseph Marikle Jun 23 '15 at 14:33
  • 1
    @Anand Looks like regex does have issues with multilingual support: http://stackoverflow.com/questions/150033/regular-expression-to-match-non-english-characters. There are a few suggestions in that thread that might help you. – Joseph Marikle Jun 23 '15 at 14:35
  • In Söderhamn, when I used the above string, it outputs S instead of Söderhamn. – Anand Jun 23 '15 at 14:44
  • 1
    @Anand based on the question I linked, this may work for you: `"Söderhamn lorem ipsum".replace(/([\u00C0-\u1FFF\u2C00-\uD7FF\w]+).*/,"$1");`. I don't know enough about the unicode sets to confirm for certain that this covers all scenarios, however. – Joseph Marikle Jun 23 '15 at 14:55
5

The quickest and easiest way is to split the string into an array based on spaces, then set it to be the first one.

var theString = "hello world";
theString = theString.split(" ")[0];
alert(theString); // alerts "hello"
Michael Low
  • 24,276
  • 16
  • 82
  • 119