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!
4 Answers
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.
-
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
-
1You 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
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.

- 31
- 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.

- 557
- 2
- 10
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
Note that this example works only with current task as OP has no delimiter or anything else but a simple string

- 5,419
- 7
- 38
- 56
-
1
-
Use a different name: `var str = "Smith, Johnista - PPP";` and you'll see. – SparoHawk Apr 01 '14 at 16:24
-
@ToKeN: Try changing the first name to "Johnny" or something else longer than 4 letters, and your code will fail. That's the problem. – agrm Apr 01 '14 at 16:25
-
-
That's is precisely the thing: it is an example for a set format. Don't assume that is all the data he has to process. ;) – SparoHawk Apr 01 '14 at 16:28
-
@SparoHawk Yea, OP's mentioned that just studying `JavaScript`, so I gave another approach to accomplish splitting string – nanobash Apr 01 '14 at 16:30