0

This is a simple question, but I'm just learning javascript. I have text "Smith, John - PPP". How can I rearrange this to just "John Smith"? Thanks!

cubanGuy
  • 1,226
  • 3
  • 26
  • 48

4 Answers4

3

Basically, you'll match a pattern in your original string, extract pieces of interest and rearrange them. A common tool to use are regular expressions.

In your example:

var s = "Smith, John - PPP";
var r = s.replace(/^([^,]+), ?([^ ]+).*$/, "$2 $1");

r will hold the substituted string.

Caveat:

Regular expressions are a helpful tool. They are no panacea. Carefully check whether the tool you are about to use is suitable for the task at hand (a screwdriver is a helpful too as well, unless you try to use it to hammer a nail into the wall) !

In particular, pattern-matching against lexical representations of semi-structured data (read: html, xml) is usually ill-advised without employing more powerful tools. If you have doubts, have a look at the accepted answer to this famous SO post.

Community
  • 1
  • 1
collapsar
  • 17,010
  • 4
  • 35
  • 61
  • Thta was fast! Thanks for replaying so quickly. it partially works, the only issue is that I want to remove the "- PPP". I added another replace(), var r = s.replace(/^([^,]+), ?([^ ]+)/, "$2 $1").replace("- PPP", ""), and it worked. Thanks again! – cubanGuy Apr 01 '14 at 16:28
  • 1
    You don't need to do the replace. Just add a `.*` to the regular expression at the end: `s.replace(/^([^,]+), ?([^ ]+).*/, "$2 $1");` – SparoHawk Apr 01 '14 at 16:32
2

Splitting and joining strings can be easy using libraries as JQuery (http://jquery.com/) but javascript allows it from base this way;

Smith, John - PPP'.split(', ')[1]

After splitting you can play with your string parts as any array:

var name = 'Smith, John - PPP';
alert(name.split(' ')[1]+' '+name.split(' ')[0].split(',')[0]); //Will alert "John Smith"

Good luck.

2

Just a quick solution using split, if the string has a constant format:

var data = 'Smith, John - PPP';
data = data.split(' - ')[0].split(', ');

var result = data[1] + ' ' + data[0];
console.log(result);

This is expanding on @ToKeN's solution.

SparoHawk
  • 557
  • 2
  • 10
1

Try with split and substr method

var str = "Smith, John - PPP";

var res = str.split(",");

console.log(res[1].substr(1,4) + res[0]); // John Smith

JSFiddle

Note that this example works only with current task as OP has no delimiter or anything else but a simple string

nanobash
  • 5,419
  • 7
  • 38
  • 56