Sandeep Thomas
Sandeep Thomas

Reputation: 4759

Removing special words from Delimitted string

Ive a situation to remove some words from a delimitted string in which the last char is ¶.

That means that if the string is:

keyword1,keyword2,keyword3¶,keyword4,keyword5¶,keyword6

The output string should be:

keyword1,keyword2,keyword4,keyword6

How can we achieve that in javascript?

This is what i did but i would like to do it without looping:

var s='keyword1,keyword2,keyword3¶,keyword4,keyword5¶,keyword6';
s=s.split(',');
var t=[];
$(s).each(function(index,element){
var lastchar=element[element.length-1];
if(lastchar!='¶')
{
t.push(element);
}
});
console.info(t.join(','));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 2

Views: 55

Answers (5)

ollazarev
ollazarev

Reputation: 1096

Problem can be solved using regular expressions:

var s='keyword1,keyword2,keyword3¶,keyword4,keyword5¶,keyword6';
s=s.replace(/,keyword\d+¶/g, '');
console.info(s);

Upvotes: 6

Marco Salerno
Marco Salerno

Reputation: 5201

This way:

var str ='keyword1,keyword2,keyword3¶,keyword4,keyword5¶,keyword6';

var keywords = str.split(",");

for(keyword in keywords){
  if(keywords[keyword].includes("¶")){
    keywords.splice(keyword,1);
  }
}

console.log(keywords);

PS: Every method loops to do it, you just can't see it in some forms ^^

Upvotes: 1

MortenMoulder
MortenMoulder

Reputation: 6646

var s = 'keyword1,keyword2,keyword3¶,keyword4,keyword5¶,keyword6';
var t = s.split(",").filter(function(word) {
    return !word.slice(-1).match(/[\u{0080}-\u{FFFF}]/gu, "");
})
console.info(t);

You can use the filter! Obviously this checks for any character that isn't ASCII. You can simply check if the last character is your .

Upvotes: 1

arbuthnott
arbuthnott

Reputation: 3819

Regular expressions should work. They are likely slower than writing your own loops, but in most cases they are clearer and you won't notice the difference.

var s='keyword1,keyword2,keyword3¶,keyword4,keyword5¶,keyword6';
console.info('original: ' + s);
var edited = s.replace(/¶.+¶/, '');
console.info('result: ' + edited);

Upvotes: 1

Thusitha
Thusitha

Reputation: 3511

You should use the filter functionality in the JS.

 var _s = "keyword1,keyword2,keyword3¶,keyword4,keyword5¶,keyword6";
 
 var _output = _s.split(",").filter(function(word){
    return (word[word.length - 1] !== "¶");
 }).join(",");
 
 console.log(_output);
   

Upvotes: 1

Related Questions