Reputation: 47945
I have a string, and I have to do 2 things on jQuery/javascript :
Tried (with some suggestions on SO) this :
var str = '00 - 12:a - Hello Maeco 4 !!!';
var parts = str.split(/^[^a-zA-Z]+/);
alert(parts[0]);
alert(parts[1]);
but it doesnt save the removed string. Any helps?
Upvotes: 0
Views: 125
Reputation: 7583
var str = '00 - 12:a - Hello Maeco 4 !!!';
var parts = str.match(/([^a-zA-Z]*)([a-zA-Z]*.*)/);
alert(parts[1]);
alert(parts[2]);
parts[1]
contains the removed string.
parts[2]
contains the rest of the string.
Upvotes: 2
Reputation: 846
You can use the str.match function, and match everything before the first alphabetic character:
var str = '00 - 12:a - Hello Maeco 4 !!!';
var parts = str.match(/^(.*?)([a-zA-Z].*)/);
alert(parts[0]);
alert(parts[1]);
alert(parts[2]);
(.*?) does a match of everything, but *? makes it non greedy, in that it finds the shortest match possible before the first alphabetic character.
EDIT
If you want to cater for the case where there is no alphabetic character, the following works:
var str = '00 - 12:';
var parts = str.match(/^(.*?)([a-zA-Z].*)?$/);
alert(parts[0]);
alert(parts[1]);
alert(parts[2]);
And in this case parts[2] is undefined. We use a ? to make the alphabetic match optional, and the $ to anchor the match to the whole string, so we still match everything if there is no alphabetic character.
Upvotes: 3
Reputation: 150020
Use parentheses in your regular expression to extract different substrings using exec
, noting that it will return an array where the first element is what the whole regex matched with subsequent elements corresponding to each of the substrings:
var str = '00 - 12:a - Hello Maeco 4 !!!';
var parts = /^([^a-zA-Z]+)(.*)/.exec(str);
alert(parts[0]); // what the whole regex matched: the whole string
alert(parts[1]); // the first part, "00 - 12:"
alert(parts[2]); // the rest, "a - Hello Maeco 4 !!!"
EDIT: Note that it doesn't actually remove anything from the original string, it doesn't change the str
variable at all. If you want to remove the first part add str = parts[2];
.
Upvotes: 2
Reputation: 39560
First, I don't think you want what you say, because this is pretty close:
var str = '00 - 12:a - Hello Maeco 4 !!!';
var before = str.replace(/[a-zA-Z]+.*$/, '');
var after = str.replace(/^[^a-zA-Z]+/, '');
See it at: http://jsfiddle.net/Ya8Yb/
The problem is that your 12:a contains with a letter.
An alternative is to try to match the pattern better:
var parts = str.match(/^(.*? - \b)([a-zA-Z].*)/);
document.write('<pre>'+str+"\n"+parts[1]+"\n"+parts[2]);
This latter one results in:
00 - 12:a -
Hello Maeco 4 !!!
Upvotes: 2
Reputation: 152
I think capturing groups would be a good option
var str = '00 - 12:a - Hello Maeco 4 !!!';
var regex /(.*?)([a-zA-Z].+)/
var match = regex.exec(str);
Then access the groups like match[1]
Upvotes: 2