How do I change the ' in a string to %27 with JavaScript? - javascript

I have this code:
var data = "I'm trying to send this with AJAX properly.";
data = encodeURIComponent(data);
data.replace("'", "%27");
data.replace(/'/, "%27");
alert(data); //Still not changed here...
I want to send that with AJAX to the database. But the ' is causing it to not send at all.
encodeURIComponent doesn't change the ' to its code %27, neither does data.replace.
What am I doing wrong here?

You're not re-assigning data.
data = data.replace("'", "%27");
replace() returns the modified string, it doesn't modify the calling object string directly.

Use the escape method, it will URL-encode a string. Note that the string.replace method only replaces the first occurence of a string when using a string as the match. To replace all instances, you have to use a regex.
var foo = escape("'");

String.prototype.replace returns the modified string, it does not modify the original. You must assign the returned value:
var newString = data.replace( "'", '%27' );

Related

replace "<0x00>" in string

Currently, I am having a problem with a string that I received after sending the command line containing the <0x00> character so how can I remove it from the string?
For example, my var string is:
<0x00>
awplus #
output:
awplus #
Use the following code to get your desired output
var string = "<0x00> awplus #";
string = string.replace("<0x00>", '');
string = string.trim();
document.write (string);
You can simply use split function and pass the string value you want to remove and then select the required part. Please note that split function returns array of string after spliting the original. You must choose the required value from the array.
I've used trim() to remove spaces around the resulting value.
Execute the following code in browser's developer console and you'll get the output.
var str = "<0x00> awplus #";
console.log(str.split('<0x00>')[1].trim());

How to make string campatible for JSON.parse()

In my application when I enter value as my"name in text field the framework makes a String like (this i can not control):
"[{\"id\":\"201500000001002\",\"name\":\"my\"name\",\"colorCode\":\"\",\"version\":\"11\",\"nodeOrder\":\"1\"}]"
Now this String is passed to JSON.parse() method which produces an error because of ambiguous name field as
\"name\":\"my\"name\"
var str = JSON.parse("[{\"id\":\"201500000001002\",\"name\":\"my\"name\",\"colorCode\":\"\",\"version\":\"11\",\"nodeOrder\":\"1\"}]")
This results in JSON exception
Is there anything I can do with the string:
"[{\"id\":\"201500000001002\",\"name\":\"my\"name\",\"colorCode\":\"\",\"version\":\"11\",\"nodeOrder\":\"1\"}]"
To escape double quote character in my " name as my \" name to make it valid for JSON.parse method.
I can not control JSON String, I am just passing name as my"name and framework creates a String which is passed to JSON.parse()
I went through a series of text replace. You can try this:
var str = "[{\"id\":\"201500000001002\",\"name\":\"my\"name\",\"colorCode\":\"\",\"version\":\"11\",\"nodeOrder\":\"1\"}]";
JSON.parse(
str.replace(/\\/i,"").
replace(/{"/g,"{'").
replace(/":"/g,"':'").
replace(/","/g,"','").
replace(/"}/g,"'}").
replace(/'/g,"\###").
replace(/"/g,"\\\"").
replace(/###/g,"\"")
);
It will give back your desired JSON array
var str = "[{\"id\":\"201500000001002\"}]";
str.replace("\"*","\\\"");
var obj = JSON.parse(str);

How to read only part of a string in Javascript

I am pulling in a string from another web page. I want to read that string into a variable but only after a certain point. Eg:
#stringexample
var variable;
I want variable to equal stringexample but not contain the # how could I do this?
This is how I am using the variable at the moment.
$("#Outputajax").load("folder/"+ variable +".html");
This is the way that works but isn't a variable.
$("#Outputajax").load("folder/webpage.html");
If you just want to trim of the first character, then you can use substring...
var input = "#stringexample";
input = input.substring(1);
//input = "stringexample"
Here is a working example
var myVariable = stringExample.replace('#','');
Could just use variable.substr(1) to cut off the first character.
If you want to specifically remove the hash from the start (but do nothing if the hash isn't there), try variable.replace(/^#/,"")
I understand you want to get everything in the string AFTER the hashtag. The other solutions will leave anything ahead of the hashtag in as well. And substring does not work if the hashtag is not the first symbol.
variable= "#stringexample".split("#")[1];
This splits the string into an array of strings, with the parameter as the point where to split, without including the parameter itself. There will be an empty string as the first parameter, and everything after the hashtag is the second string.
var slicer = function(somestring){
var parsedString = somestring;
parsedString = parsedString.slice(1);
return parsedString
}
// run from yors function with some string
var someYouVar = slicer("#something")

Remove new line characters from data recieved from node event process.stdin.on("data")

I've been looking for an answer to this, but whatever method I use it just doesn't seem to cut off the new line character at the end of my string.
Here is my code, I've attempted to use str.replace() to get rid of the new line characters as it seems to be the standard answer for this problem:
process.stdin.on("data", function(data) {
var str;
str = data.toString();
str.replace(/\r?\n|\r/g, " ");
return console.log("user typed: " + str + str + str);
});
I've repeated the str object three times in console output to test it. Here is my result:
hi
user typed: hi
hi
hi
As you can see, there are still new line characters being read between each str. I've tried a few other parameters in str.replace() but nothing seems to work in getting rid of the new line characters.
You are calling string.replace without assigning the output anywhere. The function does not modify the original string - it creates a new one - but you are not storing the returned value.
Try this:
...
str = str.replace(/\r?\n|\r/g, " ");
...
However, if you actually want to remove all whitespace from around the input (not just newline characters at the end), you should use trim:
...
str = str.trim();
...
It will likely be more efficient since it is already implemented in the Node.js binary.
You were trying to console output the value of str without updating it.
You should have done this
str = str.replace(/\r?\n|\r/g, " ");
before console output.
you need to convert the data into JSON format.
JSON.parse(data) you will remove all new line character and leave the data in JSON format.

How can I extract a URL from url("http://www.example.com")?

I need to get the URL of an element's background image with jQuery:
var foo = $('#id').css('background-image');
This results in something like url("http://www.example.com/image.gif"). How can I get just the "http://www.example.com/image.gif" part from that? typeof foo says it's a string, but the url() part makes me think that JavaScript and/or jQuery has a special URL type and that I should be able to get the location with foo.toString(). That doesn't work though.
Note that different browser implementations may return the string in a different format. For instance, one browser may return double-quotes while another browser may return the value without quotes. This makes it awkward to parse, especially when you consider that quotes are valid as URL characters.
I would say the best approach is a good old check and slice():
var imageUrlString = $('#id').css('background-image'),
quote = imageUrlString.charAt(4),
result;
if (quote == "'" || quote == '"')
result = imageUrlString.slice(5, -2);
else
result = imageUrlString.slice(4, -1);
Assuming the browser returns a valid string, this wouldn't fail. Even if an empty string were returned (ie, there is no background image), the result is an empty string.
You might want to consider regular expressions in this case:
var urlStr = 'url("http://www.foo.com/")';
var url = urlStr.replace(/^url\(['"]?([^'"]*)['"]?\);?$/, '$1');
This particular regex allows you to use formats like url(http://foo.bar/) or url("http://foo.bar/"), with single quotes instead of double quotes, or possibly with a semicolon at the end.
You could split the string at each " and get the second element:
var foo = $('#id').css('background-image').split('"')[1];
Note: This doesn't work if your URL contains quotation marks.
If it's always the same, I'd just take the substring of the URL without the prefix.
For instance, if it's always:
url("<URL>")
url("<otherURL>")
It's always the 5th index of the string to the len - 2
Not the best by all means, but probably faster than a Regex if you're not worried about other string formats.
There is no special URL type - it's a string representing a CSS url value. You can get the URL back out with a regex:
var foo = ${'#id').css('background-image');
var url = foo.match(/url\(['"](.*)['"]\)/)[1];
(that regex isn't foolproof, but it should work against whatever jQuery returns)

Categories