Removing special words from Delimitted string - javascript

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>

Problem can be solved using regular expressions:
var s='keyword1,keyword2,keyword3¶,keyword4,keyword5¶,keyword6';
s=s.replace(/,keyword\d+¶/g, '');
console.info(s);

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);

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);

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 ¶.

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 ^^

Related

return value from string prototype using javascript

I am using prototype method to replace comma in string but the function giving same string
String.prototype.removeLastComma = function(){
return this.replace(/,/g, '.');
}
String.prototype.removeLastComma = function(){
return this.replace(/,/g, '.');
}
Works just fine. I guess you're expecting the following effect:
var str = 'foo,bar,baz';
str.removeLastComma();
console.log(str); //foo.bar.baz
Unfortunately, this is not possible because the strings in JavaScript are immutable.
Try this instead:
var str = 'foo,bar,baz';
str = str.removeLastComma();
console.log(str); //foo.bar.baz
NOTE: better call your method "removeCommas" or something like that. Remove last comma means that you're going to remove only the last one.
For removing the last comma you can use the following regular expression:
String.prototype.removeLastComma = function(){
return this.replace(/,(?=[^,]*$)/, '.');
}
it works fine for me. For a sample implementation see: http://jsfiddle.net/9Hrzp/
String.prototype.removeLastComma = function(){
return this.replace(/,/g, '.');
}
alert("foo,bar".removeLastComma());

Regex remove repeated characters from a string by javascript

I have found a way to remove repeated characters from a string using regular expressions.
function RemoveDuplicates() {
var str = "aaabbbccc";
var filtered = str.replace(/[^\w\s]|(.)\1/gi, "");
alert(filtered);
}
Output: abc
this is working fine.
But if str = "aaabbbccccabbbbcccccc" then output is abcabc.
Is there any way to get only unique characters or remove all duplicates one?
Please let me know if there is any way.
A lookahead like "this, followed by something and this":
var str = "aaabbbccccabbbbcccccc";
console.log(str.replace(/(.)(?=.*\1)/g, "")); // "abc"
Note that this preserves the last occurrence of each character:
var str = "aabbccxccbbaa";
console.log(str.replace(/(.)(?=.*\1)/g, "")); // "xcba"
Without regexes, preserving order:
var str = "aabbccxccbbaa";
console.log(str.split("").filter(function(x, n, s) {
return s.indexOf(x) == n
}).join("")); // "abcx"
This is an old question, but in ES6 we can use Sets. The code looks like this:
var test = 'aaabbbcccaabbbcccaaaaaaaasa';
var result = Array.from(new Set(test)).join('');
console.log(result);

How to globally replace a forward slash in a JavaScript string?

How to globally replace a forward slash in a JavaScript string?
The following would do but only will replace one occurence:
"string".replace('/', 'ForwardSlash');
For a global replacement, or if you prefer regular expressions, you just have to escape the slash:
"string".replace(/\//g, 'ForwardSlash');
Use a regex literal with the g modifier, and escape the forward slash with a backslash so it doesn't clash with the delimiters.
var str = 'some // slashes', replacement = '';
var replaced = str.replace(/\//g, replacement);
You need to wrap the forward slash to avoid cross browser issues or //commenting out.
str = 'this/that and/if';
var newstr = str.replace(/[/]/g, 'ForwardSlash');
Without using regex (though I would only do this if the search string is user input):
var str = 'Hello/ world/ this has two slashes!';
alert(str.split('/').join(',')); // alerts 'Hello, world, this has two slashes!'
Is this what you want?
'string with / in it'.replace(/\//g, '\\');
This has worked for me in turning "//" into just "/".
str.replace(/\/\//g, '/');
Hi a small correction in the above script..
above script skipping the first character when displaying the output.
function stripSlashes(x)
{
var y = "";
for(i = 0; i < x.length; i++)
{
if(x.charAt(i) == "/")
{
y += "";
}
else
{
y+= x.charAt(i);
}
}
return y;
}
This is Christopher Lincolns idea but with correct code:
function replace(str,find,replace){
if (find){
str = str.toString();
var aStr = str.split(find);
for(var i = 0; i < aStr.length; i++) {
if (i > 0){
str = str + replace + aStr[i];
}else{
str = aStr[i];
}
}
}
return str;
}
Example Usage:
var somevariable = replace('//\\\/\/sdfas/\/\/\\\////','\/sdf','replacethis\');
Javascript global string replacement is unecessarily complicated. This function solves that problem. There is probably a small performance impact, but I'm sure its negligable.
Heres an alternative function, looks much cleaner, but is on average about 25 to 20 percent slower than the above function:
function replace(str,find,replace){
if (find){
str = str.toString().split(find).join(replace);
}
return str;
}
var str = '/questions'; // input: "/questions"
while(str.indexOf('/') != -1){
str = str.replace('/', 'http://stackoverflow.com/');
}
alert(str); // output: "http://stackoverflow.com/questions"
The proposed regex /\//g did not work for me; the rest of the line (//g, replacement);) was commented out.
You can create a RegExp object to make it a bit more readable
str.replace(new RegExp('/'), 'foobar');
If you want to replace all of them add the "g" flag
str.replace(new RegExp('/', 'g'), 'foobar');

Quick Problem - Extracting numbers from a string

I need to extract a single variable number from a string. The string always looks like this:
javascript:change(5);
with the variable being 5.
How can I isolate it? Many thanks in advance.
Here is one way, assuming the number is always surrounded by parentheses:
var str = 'javascript:change(5);';
var lastBit = str.split('(')[1];
var num = lastBit.split(')')[0];
Use regular expressions:-
var test = "javascript:change(5);"
var number = new RegExp("\\d+", "g")
var match = test.match(number);
alert(match);
A simple RegExp can solve this one:
var inputString = 'javascript:change(5);';
var results = /javascript:change\((\d+)\)/.exec(inputString);
if (results)
{
alert(results[1]); // 5
}
Using the javascript:change part in the match as well ensures that if the string isn't in the proper format, you wont get a value from the matches.
var str = 'javascript:change(5);', result = str.match(/\((\d+)\)/);
if ( result ) {
alert( result[1] )
}

JavaScript indexOf to ignore Case

I am trying to find if an image has in its source name noPic which can be in upper or lower case.
var noPic = largeSrc.indexOf("nopic");
Should I write :
var noPic = largeSrc.toLowerCase().indexOf("nopic");
But this solution doesn't work...
You can use regex with a case-insensitive modifier - admittedly not necessarily as fast as indexOf.
var noPic = largeSrc.search(/nopic/i);
No, there is no case-insensitive way to call that function. Perhaps the reason your second example doesn't work is because you are missing a call to the text() function.
Try this:
var search = "nopic";
var noPic = largeSrc.text().toLowerCase().indexOf(search.toLowerCase());
Note that if the search string is from user input you'll need to escape the special regexp characters.
Here's what it would look like:
var search = getUserInput();
/* case-insensitive search takes around 2 times more than simple indexOf() */
var regex = RegExp(search.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), "i");
var noPic = testString.search(regex);
See the updated jsperf: http://jsperf.com/regex-vs-tolowercase-then-regex/4
footnote: regexp escaping from https://stackoverflow.com/a/3561711/1333402
Try with:
var lowerCaseLargeSrc = largeSrc.toLowerCase();
var noPic = lowerCaseLargeSrc.indexOf("nopic");
Your code will only work if largeSrc is already a string. You might be getting an input that's an html element instead. So, use jQuery to resolve any potential input element into the text that's inside it. Example:
var noPic = largeSrc.text().toLowerCase().indexOf("nopic");
How about using findIndex instead that way you can do all your toLowerCase() inside the callback. Worked great for me:
// Not Supported in IE 6-11
const arr = ['HELLO', 'WORLD'];
const str = 'world';
const index = arr.findIndex(element => {
return element.toLowerCase() === str.toLowerCase();
});
console.log(index); // 👉️ 1
if (index !== -1) {
// 👉️ string is in the array
}
Credit:
https://bobbyhadz.com/blog/javascript-make-array-indexof-case-insensitive

Categories

Resources