javascript - Using regular expression can we take the even placed and odd placed value? -


var testst = "hello" testst.split('').filter((a,b)=>{if(b==0||b%2==0){return a}}).join('') // placed value hlo 

it possible looping through values, , check if index divided 2 or not. possible directly write regular expression , exec on string placed , odd placed values?

example - testst.exec(/^\d*[024]$/) //something 

something this?

console.log('abcdefghij'.replace(/(.)./g, '$1'));

the . in regexp match anything, /../ way match pair of characters. using g modifier cause pairs of characters in string matched. such match performed without overlap between matches, ab, cd, ef, gh , ij.

by putting () around first . form capture group on first character of each pair. $1 special syntax used refer first capture group, each pair replaced first character of pair.

so, example, first matching pair in string ab , a captured. ab therefore replaced a. replace cd c, ef e , on.

it worth noting string odd length final character not matched isn't problem because don't want replace it. problem if wanted swap roles of odd digits , digits, couldn't move parentheses. work we'd have make second character optional @ end of string. can using $ character, matches end of string:

// leaves trailing letter @ end, wrong  console.log('abcdefghi'.replace(/.(.)/g, '$1'));    // fixed  console.log('abcdefghi'.replace(/.(.|$)/g, '$1'));


Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -