views:

231

answers:

4

I have the following code:

var string = "word1;word2;word3,word4,word5,word6.word7";

function ends_with(string, character) {
  var regexp = new RegExp('\\w+' + character, 'g');
  var matches = string.match(regexp);
  var replacer = new RegExp(character + '$');
  return matches.map(function(ee) {
    return ee.replace(replacer, '');
  });
}
// ends_with(string, ';') => ["word1", "word2"]

The function takes no regard to whitespace. For example if you input

ends_with('Jonas Sand,', ',')

the output will be Sand. Need help on making the function work with words that has whitespace.

+2  A: 

\w matches word characters, use [^x] instead, where x is your character. This matches everything but your character.

So the first line in your function becomes

var regexp = new RegExp('[^' + character + "]+" + character, 'g');

on the other hand, if you want to match words separated by white space, use

var regexp = new RegExp('(\\w|\\s)+" + character, 'g');

 

PS: but isn't there a String#split function in javascript?

Adrian
I only want the words that ends with for example ; With your code I get the whole string
edited my answer
Adrian
+2  A: 

You can use your separator within split and take all except the last part with slice:

function ends_with(string, character) {
    return string.split(character).slice(0, -1);
}
Gumbo
`split` isn't exactly the same; his method only returns strings that _end with_ `character`; `split` will also return the last string.
SLaks
@SLaks: Ah, thanks. Fixed it with `slice`.
Gumbo
A: 

Try the following:

var string = "word1;w ord2;word3,word4,word5,word6.word7";

function ends_with(string, character) {
    var regexp = new RegExp('.+' + character, 'g');
    var matches = string.match(regexp);
    var replacer = new RegExp(character + '$');
    return matches.map(function(ee) {
        return ee.replace(replacer, '');
    });
}
SLaks
`\W|\w` is virtually any character.
Gumbo
Yes; it is. I already corrected it.
SLaks
+1  A: 

Try using '[\\w\\s]+' instead of '\\w+' to include whitespace.

Mike Nelson
Works perfectly!! Nice