Removing two words from text from string javascript - javascript

Hey I'm looking at removing words from a string, thing is the word to replace could be two different words.
e.g.
foo = "stringtest";
id = foo.replace('string', '');
or
foo = "paragraphtest";
id = foo.replace('paragraph', '');
at the moment I've approached the problem as so.
foo = "paragraphtest";
id = foo.replace('paragraph', '');
id = foo.replace('string', '');
I know this code could easily be improve but I don't know how :( thanks for your assistance.

Like this?
var foo = ["paragraph","string"];
var id = foo.replace(new RegExp(foo.join("|"),""));
The above creates array with strings you want to replace and joins it with | in RegExp constructor and replaces the match with empty string.

if(foo.indexOf("ph") > -1)
id = foo.replace('paragraph', '');
else
id = foo.replace('string', '');

Something like this maybe. Which will also give you the flexibility to modify what you replace each string with.
var replacementCharacters = [
{
searchString: "paragraph",
replacementString: ""
},
{
searchString: "string",
replacementString: ""
}
];
function runReplacement(str) {
var returnValue = str;
for (var i = 0; i < replacementCharacters.length; i++) {
returnValue = returnValue.replace(replacementCharacters[i].searchString, replacementCharacters[i].replacementString);
}
return returnValue;
}
var foo = "paragraphtest";
var id = runReplacement(foo);
Here is a demo http://jsfiddle.net/RfKt4/

Related

Creating string out of object in JavaScript

I am trying to assemble a certain string out of a JavaScript object and am having some problems.
I created a function that takes the object and should return the string. The initial object looks like so:
var testObject = {
"Topics": ["Other", "New1"],
"Other": ["try this", "this also"]
};
And I would like the string to spit out this:
"Topics~~Other|Topics~~New1|Other~~try this|Other~~this also"
Here is what I have now:
var testObject = {
"Topics": ["Other", "New1"],
"Other": ["try this", "this also"]
};
function transformObjectToString(activeFilters) {
var newString = "";
var checkFilterGroups = function(filterTopic) {
activeFilters[filterTopic].map(function(selectedFilter) {
var tempString = filterTopic + "~~" + selectedFilter + "|";
console.log("check string", tempString);
newString.concat(tempString);
});
}
for (var filterGroup in activeFilters) {
checkFilterGroups(filterGroup);
}
return newString;
}
console.log(transformObjectToString(testObject));
The temp string seems to be formatted correctly when I check the log, but, for whatever reason, it looks like the concat is not working as I assumed it would.
You should be able to just use += as this is just string concatenation. Then, all you must do is strip the last character. Here's a JSFiddle with the change https://jsfiddle.net/tfs98fxv/37/.
You can use .join('|')
var testObject = {
"Topics": ["Other", "New1"],
"Other": ["try this", "this also"]
};
function transformObjectToString(activeFilters) {
var strings = [];
var checkFilterGroups = function(filterTopic) {
activeFilters[filterTopic].map(function(selectedFilter) {
var tempString = filterTopic + "~~" + selectedFilter;
strings.push(tempString);
});
}
for (var filterGroup in activeFilters) {
checkFilterGroups(filterGroup);
}
return strings.join('|');
}
console.log(transformObjectToString(testObject));
newString = newString.concat(tempString);
this works too.
edit: how this works is, at first newString is set to null so null + tempstring at first loop, and then the newSting is set to a value, value + tempString on second loop and so on. finally you have the concatinated string in one variable which you will be returning.
edit:edit:
Also what #jfriend00 said in the comments, ditto
.concat() returns a new string so newString.concat(tempString); is not
accomplishing anything because you don't assign the result back to
newString. Remember, strings in Javascript are immutable so any
modification always creates a new string

How to extract a REGEX query string result array into a Javascript object [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Use the get paramater of the url in javascript
How can I get query string values in JavaScript?
In Javascript, how can I get the parameters of a URL string (not the current URL)?
like:
www.domain.com/?v=123&p=hello
Can I get "v" and "p" in a JSON object?
Today (2.5 years after this answer) you can safely use Array.forEach. As #ricosrealm suggests, decodeURIComponent was used in this function.
function getJsonFromUrl(url) {
if(!url) url = location.search;
var query = url.substr(1);
var result = {};
query.split("&").forEach(function(part) {
var item = part.split("=");
result[item[0]] = decodeURIComponent(item[1]);
});
return result;
}
actually it's not that simple, see the peer-review in the comments, especially:
hash based routing (#cmfolio)
array parameters (#user2368055)
proper use of decodeURIComponent and non-encoded = (#AndrewF)
non-encoded + (added by me)
For further details, see MDN article and RFC 3986.
Maybe this should go to codereview SE, but here is safer and regexp-free code:
function getJsonFromUrl(url) {
if(!url) url = location.href;
var question = url.indexOf("?");
var hash = url.indexOf("#");
if(hash==-1 && question==-1) return {};
if(hash==-1) hash = url.length;
var query = question==-1 || hash==question+1 ? url.substring(hash) :
url.substring(question+1,hash);
var result = {};
query.split("&").forEach(function(part) {
if(!part) return;
part = part.split("+").join(" "); // replace every + with space, regexp-free version
var eq = part.indexOf("=");
var key = eq>-1 ? part.substr(0,eq) : part;
var val = eq>-1 ? decodeURIComponent(part.substr(eq+1)) : "";
var from = key.indexOf("[");
if(from==-1) result[decodeURIComponent(key)] = val;
else {
var to = key.indexOf("]",from);
var index = decodeURIComponent(key.substring(from+1,to));
key = decodeURIComponent(key.substring(0,from));
if(!result[key]) result[key] = [];
if(!index) result[key].push(val);
else result[key][index] = val;
}
});
return result;
}
This function can parse even URLs like
var url = "?foo%20e[]=a%20a&foo+e[%5Bx%5D]=b&foo e[]=c";
// {"foo e": ["a a", "c", "[x]":"b"]}
var obj = getJsonFromUrl(url)["foo e"];
for(var key in obj) { // Array.forEach would skip string keys here
console.log(key,":",obj[key]);
}
/*
0 : a a
1 : c
[x] : b
*/
You could get a JavaScript object containing the parameters with something like this:
var regex = /[?&]([^=#]+)=([^&#]*)/g,
url = window.location.href,
params = {},
match;
while(match = regex.exec(url)) {
params[match[1]] = match[2];
}
The regular expression could quite likely be improved. It simply looks for name-value pairs, separated by = characters, and pairs themselves separated by & characters (or an = character for the first one). For your example, the above would result in:
{v: "123", p: "hello"}
Here's a working example.

Replace one string within array

I have the following array:
etst,tset,tets,ttest,teest,tesst,testt,4est,test,dest
I want to delete the value of an input box from the array, here's what I'm trying:
var el = document.getElementById('searchInput').value; // this is "test"
var toSearchFor = eld.slice(0,10); // the array above
for(var i=0; i < toSearchFor.length; i++) {
toSearchFor[i] = toSearchFor[i].replace(/el/g, "");
}
It's simply not replacing "test" with ""
How can I do that?
You can use Array.filter (see MDN) to filter out the desired value:
var arr = 'etst,tset,tets,ttest,teest,tesst,testt,4est,test,dest'.split(',')
,val = 'test'
document.querySelector('#result')
.innerHTML = arr.filter(function (v) {return v != val});
<div id="result"></div>
A text field example in this jsFiddle
for global replacement of a string stored in a variable u need to create an instance of RegExp explicitly, like this:
var regex = new RegExp(el, "g");
then use it in replace function:
toSearchFor[i] = toSearchFor[i].replace(regex, "");
The problem with your code is in your regular expression: /el/g. This is trying to match the letters el, instead of whatever it's in the el variable. You could have done it using the RegExp construtor.
// ...
regexp = new RegExp(el); // No need to use 'g' here since you're looking for the whole word
toSearchFor[i] = toSearchFor[i].replace(regexp, "");
// ...
Here's another way of doing it:
var eld = ['etst','tset','tets','ttest','teest','tesst','testt','4est','test','dest'];
// var el = document.getElementById('searchInput').value;
var el = 'test';
console.log(eld);
var index = eld.indexOf(el);
if (index >= 0) {
eld[index] = '';
}
console.log(eld);
Here's the output:
["etst", "tset", "tets", "ttest", "teest", "tesst", "testt", "4est", "test", "dest"]
["etst", "tset", "tets", "ttest", "teest", "tesst", "testt", "4est", "", "dest"]
In this case, we're using Array.prototype.indexOf, which returns the first index at which a given element can be found in the array, so that we can access that element directly (if found).
I hope that helps!

Creating a regex to parse html to MXML syntax

I searched a lot over stackoverflow and found very interesting that's includes:
How to create a Regular Expression for a span attribute?
And
Javascript regex to replace text div and < >
But turns out that I couldn't really manage to parse my goal to replace div with the data-type attribute and remove the data-type attribute over the strings.
Here's how I did.
//Doesn't work with multi lines, just get first occurrency and nothing more.
// Regex: /\s?data\-type\=(?:['"])?(\d+)(?:['"])?/
var source_code = $("body").html();
var rdiv = /div/gm; // remove divs
var mxml = source_code.match(/\S?data\-type\=(?:['"])?(\w+)(?:['"])?/);
var rattr =source_code.match(/\S?data\-type\=(?:['"])?(\w+)(?:['"])/gm);
var outra = source_code.replace(rdiv,'s:'+mxml[1]);
var nestr = outra.replace(rattr[0],'');// worked with only first element
console.log(nestr);
console.log(mxml);
console.log(rattr);
Over this HTML sample page
<div id="app" data-type="Application">
<div data-type="Label"></div>
<div data-type="Button"></div>
<div data-type="VBox"></div>
<div data-type="Group"></div>
</div>
Any light on that specific thing? I may missing something, but I really have no clue, there's no left space otherwise asking here.
I've created a jsFiddle to show, just open the console of browser to see the results I have with me.
http://jsfiddle.net/uWCjV/
Feel free to answer over jsfiddle or a better explanation of my regex, why it's fails.
Until I get any feedback, I will keep trying to see if I can manage to replace the text.
Thanks in advance.
It would probably be easier to parse the markup into a tree of Objects and then convert that into MXML.
Something like this:
var source_code = $("body").html();
var openStartTagRx = /^\s*<div/i;
var closeStartTagRx = /^\s*>/i;
var closeTagRx = /^\s*<\/div>/i;
var attrsRx = new RegExp(
'^\\s+' +
'(?:(data-type)|([a-z-]+))' + // group 1 is "data-type" group 2 is any attribute
'\\=' +
'(?:\'|")' +
'(.*?)' + // group 3 is the data-type or attribute value
'(?:\'|")',
'mi');
function Thing() {
this.type = undefined;
this.attrs = undefined;
this.children = undefined;
}
Thing.prototype.addAttr = function(key, value) {
this.attrs = this.attrs || {};
this.attrs[key] = value;
};
Thing.prototype.addChild = function(child) {
this.children = this.children || [];
this.children.push(child);
};
function getErrMsg(expected, str) {
return 'Malformed source, expected: ' + expected + '\n"' + str.slice(0,20) + '"';
}
function parseElm(str) {
var result,
elm,
childResult;
if (!openStartTagRx.test(str)) {
return;
}
elm = new Thing();
str = str.replace(openStartTagRx, '');
// parse attributes
result = attrsRx.exec(str);
while (result) {
if (result[1]) {
elm.type = result[3];
} else {
elm.addAttr(result[2], result[3]);
}
str = str.replace(attrsRx, '');
result = attrsRx.exec(str);
}
// close off that tag
if (!closeStartTagRx.test(str)) {
throw new Error(getErrMsg('end of opening tag', str));
}
str = str.replace(closeStartTagRx, '');
// if it has child tags
childResult = parseElm(str);
while (childResult) {
str = childResult.str;
elm.addChild(childResult.elm);
childResult = parseElm(str);
}
// the tag should have a closing tag
if (!closeTagRx.test(str)) {
throw new Error(getErrMsg('closing tag for the element', str));
}
str = str.replace(closeTagRx, '');
return {
str: str,
elm: elm
};
}
console.log(parseElm(source_code).elm);
jsFiddle
This parses the markup you provided into the following:
{
"type" : "Application"
"attrs" : { "id" : "app" },
"children" : [
{ "type" : "Label" },
{ "type" : "Button" },
{ "type" : "VBox" },
{ "type" : "Group" }
],
}
It's recursive, so embedded groups are parsed, too.

How to extract values from a string in javascript?

I need some help with extracting values from a cookie using javascript.
The string in a cookie looks something like this:
string = 'id=1||price=500||name=Item name||shipping=0||quantity=2++id=2||price=1500||name=Some other name||shipping=10||quantity=2'
By using string.split() and string.replace() and a some ugly looking code I've somehow managed to get the values i need (price, name, shipping, quantity). But the problem is that sometimes not all of the strings in the cookie are the same. Sometimes the sting in a cookie will look something like this :
string = 'id=c1||color=red||size=XL||price=500||name=Item name||shipping=0||quantity=2++id=c1||price=500||name=Item name||shipping=0||quantity=2'
with some items having color and size as parameters and sometimes only one of those.
Is there some more efficient way to explain to my computer that i want the part of the string after 'price=' to be a variable named 'price' etc.
I hope I'm making sense I've tried to be as precise as I could.
Anyway, thank you for any help
EDIT: I just wanted to say thanks to all the great people of StackOverflow for such wonderfull ideas. Because of all of your great suggestions I'm going out to get drunk tonight. Thank you all :)
Let's write a parser!
function parse(input)
{
function parseSingle(input)
{
var parts = input.split('||'),
part,
record = {};
for (var i=0; i<parts.length; i++)
{
part = parts[i].split('=');
record[part[0]] = part[1];
}
return record;
}
var parts = input.split('++'),
records = [];
for (var i=0; i<parts.length; i++)
{
records.push(parseSingle(parts[i]));
}
return records;
}
Usage:
var string = 'id=1||price=500||name=Item name||shipping=0||quantity=2++id=2||price=1500||name=Some other name||shipping=10||quantity=2';
var parsed = parse(string);
/* parsed is:
[{id: "1", price: "500", name: "Item name", shipping: "0", quantity: "2"},
{id: "2", price: "1500", name: "Some other name", shipping: "10", quantity: "2"}]
*/
You can achieve this using regular expressions. For example, the regex /price=([0-9]+)/ will match price=XXX where XXX is one or more numbers. As this part of the regex is surrounded by parenthesis it explicitly captures the numeric part for you.
var string = 'id=1||price=500||name=Item name||shipping=0||quantity=2++id=2||price=1500||name=Some other name||shipping=10||quantity=2'
var priceRegex = /price=([0-9]+)/
var match = string.match(priceRegex);
console.log(match[1]); // writes 500 to the console log
Try that:
var string = 'id=1||price=500||name=Item name||shipping=0||quantity=2++id=2||price=1500||name=Some other name||shipping=10||quantity=2';
var obj = new Array();
var arr = string.split('||');
for(var x=0; x<arr.length;x++){
var temp = arr[x].split('=');
obj[temp[0]] = temp[1]
}
alert(obj['id']); // alert 1
First, split your string into two (or more) parts by ++ separator:
var strings = myString.split('++');
then for each of the strings you want an object, right? So you need to have an array and fill it like that:
var objects = [];
for (var i = 0; i < strings.length; ++i) {
var properties = strings[i].split('||');
var obj = {};
for (var j = 0; j < properties.length; ++j) {
var prop = properties[j].split('=');
obj[prop[0]] = prop[1]; //here you add property to your object, no matter what its name is
}
objects.push(obj);
}
thus you have an array of all objects constructed from your string. Naturally, in real life I'd add some checks that strings indeed satisfy the format etc. But the idea is clear, I hope.
If you can replace the || with &, you could try to parse it as if it were a query string.
A personal note - JSON-formatted data would've been easier to work with.
I would attach the data to a javascript object.
var settingsObj = {};
var components = thatString.split('||');
for(var j = 0; j < components.length; j++)
{
var keyValue = components[j].split('=');
settingsObj[keyValue[0]] = keyValue[1];
}
// Now the key value pairs have been set, you can simply request them
var id = settingsObj.id; // 1 or c1
var name = settingsObj.name; // Item Name, etc
You're already using .split() to break down the string by || just take that a step further and split each of those sections by = and assign everything on the left the field and the right the value
This should get the first match in the string:
string.match(/price=(\d{1,})/)[1]
Note this will only match the first price= in the string, not the second one.
If you can use jQuery, it wraps working with cookies and lets you access them like:
Reading a cookie:
var comments = $.cookie('comments');
Writing a cookie:
$.cookie('comments', 'expanded');
This post by someone else has a decent example:
http://www.vagrantradio.com/2009/10/getting-and-setting-cookies-with-jquery.html
If you can't use jQuery, you need to do standard string parsing like you currently are (perhaps regular expressions instead of the string splitting / replacing might trim down your code) or find some other javascript library that you can use.
If you like eye candies in your code you can use a regexp based "search and don't replace" trick by John Resig (cached here) :
var extract = function(string) {
var o = {};
string.replace(/(.*?)=(.*?)(?:\|\||$)/g, function(all, key, value) {
o[key] = value;
});
return o;
};
Then
var objects = string.split('++'),
i = objects.length;
for (;i--;) {
objects[i] = extract(objects[i]);
}
You could do something like this, where you eval the strings when you split them.
<html>
<head>
<script type="text/javascript">
var string = 'id=c1||color=red||size=XL||price=500||name=Item name||shipping=0||quantity=2++id=c1||price=500||name=Item name||shipping=0||quantity=2'
var mySplitResult = string.split("||");
for(i = 0; i < mySplitResult.length; i++){
document.write("<br /> Element " + i + " = " + mySplitResult[i]);
var assignment = mySplitResult[i].split("=");
eval(assignment[0] + "=" + "\""+assignment[1]+"\"");
}
document.write("Price : " + price);
</script>
</head>
<body>
</body>
</html>
var str = 'id=c1||color=red||size=XL||price=500||name=Item name||shipping=0||quantity=2++id=c1||price=500||name=Item name||shipping=0||quantity=2'
var items = str.split("++");
for (var i=0; i<items.length; i++) {
var data = items[i].split("||");
for (var j=0; j<data.length; j++) {
var stuff = data[j].split("=");
var n = stuff[0];
var v = stuff[1];
eval("var "+n+"='"+v+"'");
}
alert(id);
}
EDIT: As per JamieC's suggestion, you can eliminate eval("var "+n+"='"+v+"'"); and replace it with the (somewhat) safer window[n] = v; -- but you still have the simple problem that this will overwrite existing variables, not to mention you can't tell if the variable color was set on this iteration or if this one skipped it and the last one set it. Creating an empty object before the loop and populating it inside the loop (like every other answer suggests) is a better approach in almost every way.
JSON.parse('[{' + string.replace(/\+\+/g, '},{').replace(/(\w*)=([\w\s]*)/g, '"$1":"$2"').replace(/\|\|/g, ',') + '}]')
Convert the string for JSON format, then parse it.

Categories