Split string str.split("\\") using javascript - javascript

i have a string "demo1\demo2".
var str="demo1\demo2";
console.log(str.split("\\")[1])); \\gives undefined
console.log(str.split("\")[1])); \\gives undefined
gives undefined.
i need to demo2 in console.log

You're escaping the d after the \ in str. You need to escape the \ in str:
const str = 'demo1\\demo2';
console.log(str.split('\\'));

Just like #SimpleJ already answered, you need to escape your backslash so that it is not considered to be escaping the next character itself. As proof, when you don't escape your backslash with another backslash, here is how your string gets outputted (in case you haven't checked this yourself already):
> console.log('demo1\demo2')
demo1
undefined
> console.log('demo1\\demo2')
demo1\demo2
undefined
> console.log("demo1\demo2")
demo1
undefined
> console.log("demo1\\demo2") // same goes for double quoted strings
demo1\demo2
undefined
So this is the way to go:
"demo1\\demo2".split("\\")

If the items inside need escaping, you could run it through something like this first.
If you just need 'demo2' and you know what characters it has, you could something like:
console.log(str.match(/[^a-z0-9A-Z]([a-z0-9A-Z]*)$/)[1]);
or similar.

Related

Escaping backslash in a string containing backslash

I have a string containing I\u2019m (with backslashes not escaped)
var myString = 'I\\u2019m'; // I\u2019m
But then I need a function that 'escape backslashes' that string, so the function I'm looking for would return I'm
backslashString(myString); // I'm
I've tried using eval:
function backslashString(input){
input = input.replace(/'/g, "\\'"); // Replace ' with \' that's going to mess up eval
return eval(`'${input}'`);
}
But is there a proper way of doing it? I'm looking for a function that escape backslashes a string containing I\u2019m to I'm and also handles if there's an extra backslash (A lost \ backslash)
EDIT:
I did not ask what I meant from the start. This not only applies to unicode characters, but applies to all backslash characters including \n
The backslashes aren’t the real problem here - the real problem is the difference between code and data.
\uXXXX is JavaScript syntax to write the Unicode codepoint of a character in a text literal. It gets replaced with the actual character, when the JavaScript parser interprets this code.
Now you have a variable that contains the value I\u2019m already - that is data. This does not get parsed as JavaScript, so it does mean the literal characters I\u2019m, and not I’m. eval can “fix” that, because the missing step of interpreting this as code is simply what eval does.
If you do not want to use eval (and thereby invite all the potential risks that entails, if the input data is not completely under your control), then you can parse those numeric values from the string using regular expressions, and then use String.formCharCode to create the actual Unicode character from the given code point:
var myString = 'I\\u2019m and I\\u2018m';
var myNewString = myString.replace(/\\u([0-9]+)/g, function(m, n) {
return String.fromCharCode(parseInt(n, 16)) }
);
console.log(myNewString)
/\\u([0-9]+)/g - regular expression to match this \uXXXX format (X=digits), g modifier to replace all matches instead of stopping after the first.
parseInt(n, 16) - to convert the hexadecimal value to a decimal first, because String.fromCharCode wants the latter.
decodeURIComponent(JSON.parse('"I\\u2019m"'));
OR for multiple
'I\\\u2019m'.split('\\').join().replace(/,/g,'');
'I\u2019m'.split('\\').join().replace(/,/g,'');
Looks like there's no other way other than eval (JSON.parse doesn't like new lines in strings)
NOTE: The function would return false if it has a trailing backslash
function backslashString(input){
input = input.replace(/`/g, '\\`'); // Escape quotes for input to eval
try{
return eval('`'+input+'`');
}catch(e){ // Will return false if input has errors in backslashing
return false;
}
}

JSON.stringify - Strange behaviour with backslash in array

I was playing with JS while I noticed a strange behaviour with backslash \ inserted into a string within an array printed using JSON.stringify(). Of course the backslash is used to escaping special chars, but what happens if we need to put backslash in a string? Just use backslash to escape itself you're thinking, but it doesn't work with JSON.stringify
This should print one backslash
array = ['\\'];
document.write(JSON.stringify(array));
This should print two backslashes
array = ['\\\\'];
document.write(JSON.stringify(array));
Am I missing something? Could be that considered as a bug of JSON.stringify?
It is correct. JSON.stringify will return the required string to recreate that object - as your string requires that you escape a backslash, it will also return the required escape backslash to generate the string properly.
Try this:
array = ['\\'];
var x = JSON.stringify(array)
var y = JSON.parse(x)
if (array[0] == y[0]) alert("it works")
or
array = ['\\'];
if (JSON.parse(JSON.stringify(array))[0] == array[0]) alert("it really works")

Trimming String in Javascript

I have string like var a=""abcd""efgh"".How do I print the output as abcd""efgh by removing first and last double quote of a string I used a.replace(/["]/g,'') but it is removing all the double quotes of a string.How do i get the output as abcd""efgh.Suggest me an idea.
You can use
var a='"abcd""efgh"';
a.replace(/^"+|"+$/g, '');
From the comments here is the explanation
Explanation
There are 2 parts ^"+ and "+$ separated by | which is the regex equivalent of the or
^ is for starts-with and "+ is for one or more "
Similarly $ is for ends-with
The //g is for global replacement otherwise the only the first occurrence will be replaced
Try use this
var a='"abcd""efgh"';
a.replace(/^"|"$/g, '');

new RegExp. test

I have posted a problem in the above link - regExpression.test.
Based on that I have done like bellow that also produces an error.
var regExpression=new RegExp("^([a-zA-Z0-9_\-\.]+)$");
alert (regExpression.test("11aa"));
You need to escape your \ since you're declaring it with a string, like this:
var regExpression=new RegExp("^([a-zA-Z0-9_\\-\\.]+)$");
^ ^ add these
You can test it here.
You can also use the literal RegExp syntax /…/:
var regExpression = /^([a-zA-Z0-9_\-\.]+)$/;
By the way: The . does not need to be escaped in character classes anyway. And if you put the range operator at the begin or the end of the character class or immediately after a character range, it doesn’t need to be escaped either:
var regExpression = /^([a-zA-Z0-9_.-]+)$/;

# symbol for strings in jQuery

if (confirm('<%=Ns1.Ns2.MyClass.GetResourceText("DeleteConfirmationMessage")%>')) { /* something to do...*/ }
I have a jQuery expression as above. But the return value of GetResourceText method is a very long string. So my page renders the function like below:
if (confirm('
Are you sure lablabla? If you delete this lablabla...
lablabla...
')) {
Because of this my jQuery functions do not work. Is there a symbol for jQuery like # that we use in C#?
Note: jQuery is not a special language, that would be javascript.
You will have to pass this string though an extra method that replaces all newlines with the string "\n". Take care when doing this from C#: you need the literal string "\n" so you will need escaping, either #"\n" or "\\n".
You also will need to watch out for quotes: a message like "call O'Brien" will fail with a javascript error. Replace that with "&apos;".
\. Just place it at the end of the line:
var str = "this \
is on more \
than one line \
and is valid.";
alert(str); // alerts "this is on more than one line and is valid."

Categories

Resources