Domanda

I am using this as keyword s='young girl jumping'

function selfreplace(s) {
    var words = ['man', 'jumping'];
    var re = new RegExp('\\b(' + words.join('|') + ')\\b', 'g');
    var specials = [];
    var match;
    var str = "";
    while(match = re.exec(s)) {
        str += match[0] + '(k)';
    }
    return str;
}

It is returning jumping(k)

I want the result to be young(s) girl(s) jumping(k)

È stato utile?

Soluzione

It would probably be easiest to check if it's in words outside of the regex:

function selfreplace(s) {
   var words = ['man','jumping'];
   var re = new RegExp('\\b(\\w+)\\b', 'g');   
   var specials = [];
   var match;
   var str = "";
   while(match = re.exec(s))
   {
       if (words.indexOf(match[0]) !== -1))
           str += match[0] + '(k)';
       else
           str += match[0] + '(s)';
   }    
   return str;

}

Altri suggerimenti

You can use a replace with callback.

function selfreplace(s){
  return s.replace(/man|jumping|(\w+)/g, function(word, misc){
    return word + (misc? '(s)' : '(k)')
  })
}

If the word matched is man or jumping, only the first argument (entire match) is set. If the word matched is any other, the first capturing group is set as well.

If you don't know the set of words ahead, you can still generate the regex on the fly. Assuming words don't contain non-word characters:

function selfreplace(s, words){ //or any other method of passing 'words'
  var re = RegExp(words.join("|")+"|(\\w+)",'g');
  return s.replace(re, function(word, misc){
    return word + (misc? '(s)' : '(k)')
  })
}

Just a different approach, probably not the best solution but thought i'd throw it out there.

var str = "young girl jumping";

function replaceStr(s){

    var matched = new RegExp("man|jumping", "i");
    var newStr = "";
    var str = s.split(" ");
    for(var i=0; i<str.length;i++){
        if(str[i].match(matched)){
            newStr += str[i]+"(k) ";
        } else {
            newStr += str[i]+"(s) ";
        }
    }
    return newStr.substr(0, newStr.length-1); 
}

//replaceStr(str) returns "young(s) girl(s) jumping(k)"

DEMO here

if the matched words might change then you can always amend this function so it accepts an array as the second argument and then creates the regexp dynamically

replaceStr(s, matchArr){} and var matched = new RegExp("("+matchArr.join("|")+")", "i");

Something like this might give you a hint:

var s = "young girl jumping",
    words = ['man','jumping'],
    regex = new RegExp("(" + words.join("|") +")", "g"),
    q = s.replace(regex, function( string ) {
        return string + "(k)";
    });

console.log(q); // "young girl jumping(k)"

If you match words only, you do not really need regexps at all, do you?

What about just looking for the words with ==

function selfreplace(s) {
    var words = ['man','jumping'];
    var input = s.split(" ");
    var str = "";
    for(var i=0; i<input.length; i++){
        var tmpString = "(s)";
        for(var j=0; j<words.length; j++){
            if(input[i] == words[j]){
                tmpString = "(k)";
            }
        }
        str += input[i]+tmpString;
    }
    return str;
}

You could use a RegExp for this, but for what you are doing a RegExp is overkill. I would use Array methods instead:

var selfreplace = function selfreplace(s) {
    var words = ['man', 'jumping'],
        i = 0,
        suffix = '(s)';
    s = s.split(' ');
    for (i = 0; i < s.length; i += 1) {
        if (words.indexOf(s[i]) > -1) {
            s[i] = s[i] + '(k)';
        } else {
            s[i] = s[i] + '(s)';
        }
    }
    return s.join(' ');
};

Here's a fiddle in action: http://jsfiddle.net/4KAzw/

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top