Replace last letters in array of strings Javascript - javascript

I need to do as follows:
I've got an array of strings containing last names. Some of them ends with letter 'i'.
manLastNames = ["testowski","bucz","idzikowski","gosz"];
I need to make a function which will iterate over this array of strings and if there is an element ending with 'i', I need to replace this 'i' for 'a', otherwise just leave string as it is.
At the end I want to have another array where all last 'i's are replaced with 'a's.
womanLastNames = ["testowska","bucz","idzikowska","gosz"];
This is what I have now, but Im pretty sure that it start being crap at some point
var rep = function() {
var manLastNames = ["testowski","bucz","idzkowski","gosz"];
var womanLastNames = new Array(4);
for (var i=0; i<manLastNames.length; i++) {
var lastName = manLastNames[i];
if (lastName.substr(lastName.length - 1, 1) == 'i') {
lastName = lastName.substr(0, lastName.length - 1) + 'a';
}
}
for (var i=0; i<womanLastNames.length; i++) {
womanLastNames[i] = lastName[i];
}
console.log(womanLastNames);
}
rep();

Try the code:
var manNames = ["testowski","bucz","idzkowski","gosz"];
var womanNames = manNames.map(function(name) {
return name.endsWith("i") ? name.slice(0, -1) + "a" : name;
});
console.log(womanNames)
If your interpreter supports ES6, the following is equivalent:
names.map((name)=>name.endsWith("i") ? name.slice(0, -1) + "a" : name)

Here is solution
var rep = function() {
var manLastNames = ["testowski","bucz","idzkowski","gosz"];
var womanLastNames =[];
for (var i=0; i<manLastNames.length; i++) {
var lastName = manLastNames[i];
if (lastName.charAt(lastName.length - 1) == 'i') {
lastName = lastName.substr(0, lastName.length - 1) + 'a';
}
womanLastNames.push(lastName);
}
console.log(womanLastNames);
}
rep();
Another solution is to use .map method like this, using a callback function:
var manLastNames = ["testowski","bucz","idzikowski","gosz"];
function mapNames(item){
return item[item.length-1]=='i' ? item.substr(0, item.length-1) + "a" : item;
}
console.log(manLastNames.map(mapNames));

Depending on how efficient you need to be, you can use regular expressions to do both tasks:
var new_name = name.replace(/i$/, 'a');
will replace the last "i" in a string with "a" if it exists
var new_name = name.replace(/i/g, 'a');
will replace all "i"s in a string with "a".
var names = ["testowski", "bucz", "idzkowski", "gosz"];
console.log("original", names);
var last_i_replaced = names.map(function(name) {
return name.replace(/i$/, 'a');
});
console.log("last 'i' replaced", last_i_replaced);
var all_i_replaced = names.map(function(name) {
return name.replace(/i/g, 'a');
});
console.log("all 'i's replaced", all_i_replaced);

This should work:
var rep = function() {
var manLastNames = ["testowski","bucz","idzkowski","gosz"];
var womanLastNames = manLastNames;
for(var i=0; i<manLastNames.length;i++){
if(manLastNames[i].charAt(manLastNames[i].length-1)=='i'){
womanLastNames[i]=manLastNames[i].substr(0,womanLastNames[i].length-1)+'a';
}
}
console.log(womanLastNames);
}
rep();

Here is another solution
var manLastNames = ["testowski","bucz","idzkowski","gosz"];
var womanLastNames = []
manLastNames.forEach(x => {
if (x.charAt(x.length-1) === "i") womanLastNames.push(x.slice(0,-1).concat("a"));
else womanLastNames.push(x);
});
console.log(womanLastNames);

Related

Split array by tag and delete all similar element

I have some html page with text and need to output all inner HTML from tag b by alphabetical order in lower case. I'm just a begginer, so don't be strict.
My code is here (text is just for example): http://jsfiddle.net/pamjaranka/ebeptLzj/1/
Now I want to: 1) save upper case for inner HTML from tag abbr; 2) delete all similar element from the array (as MABs).
I was trying to find the way to split the array by tag, but all that I've done is:
for(var i=0; i<allbold.length; i++){
labels[i] = allbold[i].innerHTML;
}
var searchTerm = ['abbr'];
var abbr = [];
var keywordIndex;
$.each(labels, function(i) {
$.each(searchTerm, function(j) {
var rSearchTerm = new RegExp('\\b' + searchTerm[j] + '\\b','i');
if (labels[i].match(rSearchTerm)) {
keywordIndex = i;
for(var j=0; j<labels.length; j++){
abbr[i] = labels[i];
}
}
});
});
Vanilla JS solution (no library required, see jsFiddle):
var allbold = document.querySelectorAll("b"),
words = document.querySelector("#words"),
labels = {}, i, word, keys, label;
// first, collect all words in an object (this eliminates duplicates)
for(i = 0; i < allbold.length; i++) {
word = allbold[i].textContent.trim();
if (word === 'Labels:') continue;
labels[word.toLowerCase()] = word;
}
// then sort the object keys and output the words in original case
keys = Object.keys(labels).sort();
for(i = 0; i < keys.length; i++){
label = document.createTextNode("SPAN");
label.textContent = labels[keys[i]];
words.appendChild(label);
// add a comma if necessary
if (i < keys.length - 1) {
words.appendChild(document.createTextNode(", "));
}
}
with one helper:
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g, "");
};
jQuery solution (see jsFiddle):
$(".content b").map(function () {
return $("<span>", {text: $.trim(this.textContent)})[0];
}).unique(function () {
return lCaseText(this);
}).sort(function (a, b) {
return lCaseText(a) < lCaseText(b) ? -1 : 1;
}).appendTo("#words");
with two helpers:
$.fn.extend({
unique: function (keyFunc) {
var keys = {};
return this.map(function () {
var key = keyFunc.apply(this);
if (!keys.hasOwnProperty(key)) {
keys[key] = true;
return this;
}
});
}
});
function lCaseText(element) {
return element.textContent.toLowerCase();
}
use the mapping element Is THIS FIDDLE for all upper case else this fiddle after your comment what you need
var maplabels = [];
for(var i=0; i<allbold.length; i++){
if (allbold[i].innerHTML != "Labels:") {
if(maplabels.indexOf(allbold[i].innerHTML) == -1){
maplabels.push(allbold[i].innerHTML);
labels.push('<i>' + allbold[i].innerHTML.toUpperCase() + '</i>');
}
}
}

change array to json

I've been playing around with javascript and casperjs. I have the following lines of code.
casper.thenOpen('somesite', function() {
console.log('clicked ok, new location is ' + this.getCurrentUrl());
// Get info on all elements matching this CSS selector
var town_selector = 'div tr';
var town_names_info = this.getElementsInfo(town_selector); // an array of object literals
// Pull out the town name text and push into the town_names array
var town_names = [];
for (var i = 0; i < town_names_info.length; i++) {
town_names.push(town_names_info[i].text.trim());}
// Dump the town_names array to screen
utils.dump(town_names);
casper.capture('capture5.png');
});
my output is this.
[
"Address:\n \n address",
"City:\n \ncity",
"State:\n \nstate",
"Zip:\n \nzip",
]
how can I make it json? like this.
{
"Address":"address",
"City":"city",
"State":"state",
"Zip":"zip"
}
Thanks in advance.
You can use something like this:
function arrayToObject(arr) {
var out = {};
arr.forEach(function (element) {
var keyvalue = element.replace(/[\n\s]+/, '').split(':');
var key = keyvalue[0];
var value = keyvalue[1];
out[key] = value;
});
return out;
}
then you can do:
var json = JSON.stringify(arrayToObject(myArray));
Update:
> How can I change this to split only the first occurrence of colon?
Use this:
arr.forEach(function (element) {
var keyvalue = element.replace(/[\n\s]+/, '');
var key = keyvalue.substring(0, element.indexOf(':'));
var value = keyvalue.substring(key.length + 1);
out[key] = value;
});

How to replace only first sequential occurences (fuzzymatch)?

I'm trying to write "fuzzy" match and I can't find a way to solve this problem:
Data in: makrusakkk, query: mrk, expected result: <b>m</b>ak<b>r</b>usa<b>k</b>kk.
RegExp: "makrusakkk".match(/(m).*?(r).*?(k)/i) returns ["makrusak", "m", "r", "k"].
So the question is: is there a way to get the expected result using RegExp?
I think using regular expression for such problem makes things just more complicated. The following string and loop based solution would lead to the result:
function fuzzySearch(query, input) {
var inds = patternMatches(query, input);
if(!inds) return input;
var result = input;
for(var i = inds.length - 1; i >= 0; i--) {
var index = inds[i];
result = result.substr(0,index) +
"<b>" + result[index] + "</b>" +
result.substr(index+1);
}
return result;
}
function patternMatches(query, input) {
if(query.length <= 0) {
return [];
} else if(query.length == 1) {
if(input[0] == query[0]) return [0];
else return [];
} else {
if(input[0] != query[0])
return false;
var inds = [0];
for(var i = 1; i < query.length; i++) {
var foundInd = input.indexOf(query[i], inds[i-1]);
if(foundInd < 0) {
return [];
} else {
inds.push(foundInd);
}
}
return inds;
}
}
var input = "makrusakkksd";
var query = "mrk";
console.log(fuzzySearch(query, input));
console.log(patternMatches(query, input));
Here's a live demo too: http://jsfiddle.net/sinairv/T2MF4/
Here you will need for:
function search_for_it(txt, arr){
for(i=0;i<arr.length;i++){
var reg = new RegExp(arr[i], "i");
txt = txt.replace(reg, "<b>"+arr[i]+"</b>");
}
return txt;
}
search_for_it("makrusakkk", ["m","r","k"]);
//return "<b>m</b>a<b>k</b><b>r</b>usakkk"
PS: Your expected result is incorrect. There is a k after the first a.
is there a way to get an expected result using RegExp?
There is.
"makrusakkk".replace(/(m)(.*?)(r)(.*?)(k)/i, '<b>$1</b>$2<b>$3</b>$4<b>$5</b>'​​​​​​​)
I feel vaguely dirty for this, but...regardless; here's one way to do it:
$('#s').keyup(
function(e) {
var w = e.which;
if (w == 8 || w == 46) {
return false;
}
var listElems = $('ul:first li'),
search = $(this).val().replace(/w+/g, ''),
r = search.split(''),
rString = [];
$.each(r, function(i, v) {
rString.push('(' + v + ')');
});
var reg = new RegExp(rString.join('(\\d|\\D)*'), 'gi');
listElems.each(
function() {
if (!$(this).attr('data-origtext')) {
$(this).attr('data-origtext', $(this).text());
}
$(this).html($(this).attr('data-origtext').replace(reg, '<b>$&</b>'));
});
});​
JS Fiddle demo.
It could, almost certainly, benefit from quite some simplification though.
References:
attr().
:first selector.
join().
keyup().
push().
RegExp().
replace().
split().
text().
val().

JavaScript - Improve the URL parameter fetching algorithm

I need to get the URL search paramentes in an object, for eg; http://example.com/?a=x&b=y&d#pqr should yield {a:x, b:y, d:1}
Below is the method i used to get this, How can i improve this? any suggessions...
var urlParamKeyVals = new Array();
var pieces = new Array();
var UrlParams = {};
if(window.location.search.length){
var urlSearchString = window.location.search;
if(urlSearchString.charAt(0) == '?'){
urlSearchString = urlSearchString.substr(1);
urlParamKeyVals = urlSearchString.split("&");
}
}
for (var i = 0; i<urlParamKeyVals .length; i++) {
pieces = urlParamKeyVals [i].split("=");
if(pieces.length==1){
UrlParams[pieces[0]]=1;
} else {
UrlParams[pieces[0]]=pieces[1];
}
}
UrlParams;
I've made some time ago a small function for the same purpose:
Edit: To handle empty keys as 1:
function getQueryStringValues (str) {
str = str || window.location.search;
var result = {};
str.replace(/([^?=&]+)(?:[&#]|=([^&#]*))/g, function (match, key, value) {
result[key] = value || 1;
});
return result;
}
getQueryStringValues("http://example.com/?a=x&b=c&d#pqr");
// returns { a="x", b="c", d=1 }
function getParams(q){
var p, reg = /[?&]([^=#&]+)(?:=([^&#]*))?/g, params = {};
while(p = reg.exec(q)){
params[decodeURIComponent(p[1])] = p[2] ? decodeURIComponent(p[2]) : 1;
}
return params;
}
getParams(location.search);
-- edit
I extended the regular expression to match also the &param (no value) and &param= (empty value) cases. In both cases the value 1 is returned. It should also stop extracting on hash (#) character. Decoding values also supported.
jQuery bbq has a nice deparam method if you are trying to look at some very stable code:
http://github.com/cowboy/jquery-bbq/
http://benalman.com/code/projects/jquery-bbq/examples/deparam/
function getObjectFromSearch() {
var search = location.search;
var searchTerms = [];
var obj = {};
if (search !== '') {
search = search.replace(/^\?/,'');
searchTerms = search.split("&");
}
for (var i=0, imax=searchTerms.length; i<imax; i++) {
var ary = searchTerms[i].split("=");
obj[ary[0]] = ary[1];
}
return obj;
}

Splitting a string only when the delimeter is not enclosed in quotation marks

I need to write a split function in JavaScript that splits a string into an array, on a comma...but the comma must not be enclosed in quotation marks (' and ").
Here are three examples and how the result (an array) should be:
"peanut, butter, jelly"
-> ["peanut", "butter", "jelly"]
"peanut, 'butter, bread', 'jelly'"
-> ["peanut", "butter, bread", "jelly"]
'peanut, "butter, bread", "jelly"'
-> ["peanut", 'butter, bread', "jelly"]
The reason I cannot use JavaScript's split method is because it also splits when the delimiter is enclosed in quotation marks.
How can I accomplish this, maybe with a regular expression ?
As regards the context, I will be using this to split the arguments passed from the third element of the third argument passed to the function you create when extending the jQuery's $.expr[':']. Normally, the name given to this parameter is called meta, which is an array that contains certain info about the filter.
Anyways, the third element of this array is a string which contains the parameters that are passed with the filter; and since the parameters in a string format, I need to be able to split them correctly for parsing.
What you are asking for is essentially a Javascript CSV parser. Do a Google search on "Javascript CSV Parser" and you'll get lots of hits, many with complete scripts. See also Javascript code to parse CSV data
Well, I already have a jackhammer of a solution written (general code written for something else), so just for kicks . . .
function Lexer () {
this.setIndex = false;
this.useNew = false;
for (var i = 0; i < arguments.length; ++i) {
var arg = arguments [i];
if (arg === Lexer.USE_NEW) {
this.useNew = true;
}
else if (arg === Lexer.SET_INDEX) {
this.setIndex = Lexer.DEFAULT_INDEX;
}
else if (arg instanceof Lexer.SET_INDEX) {
this.setIndex = arg.indexProp;
}
}
this.rules = [];
this.errorLexeme = null;
}
Lexer.NULL_LEXEME = {};
Lexer.ERROR_LEXEME = {
toString: function () {
return "[object Lexer.ERROR_LEXEME]";
}
};
Lexer.DEFAULT_INDEX = "index";
Lexer.USE_NEW = {};
Lexer.SET_INDEX = function (indexProp) {
if ( !(this instanceof arguments.callee)) {
return new arguments.callee.apply (this, arguments);
}
if (indexProp === undefined) {
indexProp = Lexer.DEFAULT_INDEX;
}
this.indexProp = indexProp;
};
(function () {
var New = (function () {
var fs = [];
return function () {
var f = fs [arguments.length];
if (f) {
return f.apply (this, arguments);
}
var argStrs = [];
for (var i = 0; i < arguments.length; ++i) {
argStrs.push ("a[" + i + "]");
}
f = new Function ("var a=arguments;return new this(" + argStrs.join () + ");");
if (arguments.length < 100) {
fs [arguments.length] = f;
}
return f.apply (this, arguments);
};
}) ();
var flagMap = [
["global", "g"]
, ["ignoreCase", "i"]
, ["multiline", "m"]
, ["sticky", "y"]
];
function getFlags (regex) {
var flags = "";
for (var i = 0; i < flagMap.length; ++i) {
if (regex [flagMap [i] [0]]) {
flags += flagMap [i] [1];
}
}
return flags;
}
function not (x) {
return function (y) {
return x !== y;
};
}
function Rule (regex, lexeme) {
if (!regex.global) {
var flags = "g" + getFlags (regex);
regex = new RegExp (regex.source, flags);
}
this.regex = regex;
this.lexeme = lexeme;
}
Lexer.prototype = {
constructor: Lexer
, addRule: function (regex, lexeme) {
var rule = new Rule (regex, lexeme);
this.rules.push (rule);
}
, setErrorLexeme: function (lexeme) {
this.errorLexeme = lexeme;
}
, runLexeme: function (lexeme, exec) {
if (typeof lexeme !== "function") {
return lexeme;
}
var args = exec.concat (exec.index, exec.input);
if (this.useNew) {
return New.apply (lexeme, args);
}
return lexeme.apply (null, args);
}
, lex: function (str) {
var index = 0;
var lexemes = [];
if (this.setIndex) {
lexemes.push = function () {
for (var i = 0; i < arguments.length; ++i) {
if (arguments [i]) {
arguments [i] [this.setIndex] = index;
}
}
return Array.prototype.push.apply (this, arguments);
};
}
while (index < str.length) {
var bestExec = null;
var bestRule = null;
for (var i = 0; i < this.rules.length; ++i) {
var rule = this.rules [i];
rule.regex.lastIndex = index;
var exec = rule.regex.exec (str);
if (exec) {
var doUpdate = !bestExec
|| (exec.index < bestExec.index)
|| (exec.index === bestExec.index && exec [0].length > bestExec [0].length)
;
if (doUpdate) {
bestExec = exec;
bestRule = rule;
}
}
}
if (!bestExec) {
if (this.errorLexeme) {
lexemes.push (this.errorLexeme);
return lexemes.filter (not (Lexer.NULL_LEXEME));
}
++index;
}
else {
if (this.errorLexeme && index !== bestExec.index) {
lexemes.push (this.errorLexeme);
}
var lexeme = this.runLexeme (bestRule.lexeme, bestExec);
lexemes.push (lexeme);
}
index = bestRule.regex.lastIndex;
}
return lexemes.filter (not (Lexer.NULL_LEXEME));
}
};
}) ();
if (!Array.prototype.filter) {
Array.prototype.filter = function (fun) {
var len = this.length >>> 0;
var res = [];
var thisp = arguments [1];
for (var i = 0; i < len; ++i) {
if (i in this) {
var val = this [i];
if (fun.call (thisp, val, i, this)) {
res.push (val);
}
}
}
return res;
};
}
Now to use the code for your problem:
function trim (str) {
str = str.replace (/^\s+/, "");
str = str.replace (/\s+$/, "");
return str;
}
var splitter = new Lexer ();
splitter.setErrorLexeme (Lexer.ERROR_LEXEME);
splitter.addRule (/[^,"]*"[^"]*"[^,"]*/g, trim);
splitter.addRule (/[^,']*'[^']*'[^,']*/g, trim);
splitter.addRule (/[^,"']+/g, trim);
splitter.addRule (/,/g, Lexer.NULL_LEXEME);
var strs = [
"peanut, butter, jelly"
, "peanut, 'butter, bread', 'jelly'"
, 'peanut, "butter, bread", "jelly"'
];
// NOTE: I'm lazy here, so I'm using Array.prototype.map,
// which isn't supported in all browsers.
var splitStrs = strs.map (function (str) {
return splitter.lex (str);
});
var str = 'text, foo, "haha, dude", bar';
var fragments = str.match(/[a-z]+|(['"]).*?\1/g);
Even better (supports escaped " or ' inside the strings):
var str = 'text_123 space, foo, "text, here\", dude", bar, \'one, two\', blob';
var fragments = str.match(/[^"', ][^"',]+[^"', ]|(["'])(?:[^\1\\\\]|\\\\.)*\1/g);
// Result:
0: text_123 space
1: foo
2: "text, here\", dude"
3: bar
4: 'one, two'
5: blob
If you can control the input to enforce that the string will be enclosed in double-quotes " and that all elements withing the string will be enclosed in single-quotes ', and that no element can CONTAIN a single-quote, then you can split on , '. If you CAN'T control the input, then using a regular expression to sort/filter/split the input would be about as useful as using a regular expression to match against xhtml (see: RegEx match open tags except XHTML self-contained tags)

Categories

Resources