Replace Characters from string with javascript - javascript

I have a string like (which is a shared path)
\\cnyc12p20005c\mkt$\\XYZ\
I need to replace all \\ with single slash so that I can display it in textbox. Since it's a shared path the starting \\ should not be removed. All others can be removed.
How can I achieve this in JavaScript?

You could do it like this:
var newStr = str.replace(/(.)\\{2}/, "$1\\");
Or this, if you don't like having boobs in your code:
var newStr = "\\" + str.split(/\\{1,2}/).join("\\");

You can use regular expression to achieve this:
var s = '\\\\cnyc12p20005c\\mkt$\\\\XYZ\\';
console.log(s.replace(/.\\\\/g, '\\')); //will output \\cnyc12p20005c\mkt$\XYZ\
Double backslashes are used because backslash is special character and need to be escaped.

Related

How to remove the special characters from a string using javascript

I have the below String value to be displayed in text area and i want to remove the first characters ##*n|n from the string .
The string is as follows :
Symbol-001
##*n|nClaimant Name
##*n|nTransaction
I have used the below code to deal with removing the special characters
var paramVal1 = parent.noteText; //paramVal1 will have the string now
var pattern = /[##*n|n]/g;
var paramVal1 = paramVal1.replace(pattern,'');
document.getElementById("txtNoteArea").value = paramval1;//appending the refined string to text area
For the above used code am getting the out put string as below
Symbol-001
|Claimat Name //here 'n' is missing and i have an extra '|' character
|Transactio //'n' is missing here too and an extra '|' character
Kindly help to remove the characters ##*n|n without affecting the other values
What your regex is saying is "remove any of the following characters: #|*n". Clearly this isn't what you want!
Try this instead: /##\*n\|n/g
This says "remove the literal string ##*n|n". The backslashes remove the special meaning from * and |.
You are using regular expression reserved chars in your pattern, you need to escape them
You can use this expression:
var pattern = /[\#\#\*n\|n]/g;
i think use this /[##*n\|n]/g regEx
If you want to replace the first occurrence as you say on your question, you don't need to use regex. A simple string will do, as long as you escape the asterisk:
var str = "Symbol-001 ##*n|nClaimant Name ##*n|nTransaction";
var str2 = str.replace("##\*n|n", ""); //output: "Symbol-001 Claimant Name ##*n|nTransaction"
If you want to replace all the occurrences, you can use regex, escaping all the characters that have a special meaning:
var str3 = str.replace(/\#\#\*n\|n/g, ""); //output: "Symbol-001 Claimant Name Transaction"
Have a look at this regex builder, might come in handy - http://gskinner.com/RegExr/

Replace single backslash "\" with double backslashes "\\"

I have string with file path. I want to replace all single backslashes ("\") with double backslashes ("\\").
var replaceableString = "c:\asd\flkj\klsd\ffjkl";
var part = /#"\\"/g;
var filePath = replaceableString .replace(part, /#"\\"/);
console.log(filePath);
Console showed me it.
c:asdlkjklsdfjkl
I found something like this, unfortunately it didn't work.
Replacing \ with \\
Try:
var parts = replaceableString.split('\\');
var output = parts.join('\\\\');
Personally, as I am not so expert in reg exps, I tend to avoid them when dealing with non-alphanumeric characters, both due to readability and to avoid weird mistake.
var replaceableString = "c:\asd\flkj\klsd\ffjkl";
alert(replaceableString);
This will alert you c:asdlkjklsdfjkl because '\' is an escape character which will not be considered.
To have a backslash in your string , you should do something like this..
var replaceableString = "c:\\asd\\flkj\\klsd\\ffjkl";
alert(replaceableString);
This will alert you c:\asd\flkj\klsd\ffjkl
JS Fiddle
Learn about Escape sequences here
If you want your string to have '\' by default , you should escape it .. Use escape() function
var replaceableString = escape("c:\asd\flkj\klsd\ffjkl");
alert(replaceableString);
JS Fiddle
You have several problems in your code.
To get a \ in your string variable you need to escape it.
When you create a string like this: replaceableString = "c:\asd\flkj\klsd\ffjkl"; characters with a \ before are treated as escape sequences. So during the string creation, it tries to interpret the escape sequence \a, since this is not valid it stores the a to the string. E.g. \n would have been interpreted as newline.
I assume the # is coming from a .net example. Javascript does not know "raw" strings.
remove the quotes from your regex.
This would do what you want:
var string = "c:\\asd\\flkj\\klsd\\ffjkl";
var regex = /\\/g;
var FilePath = string.replace(regex, "\\\\");
Here is the answer:
For replacing single backslash with single forward slash:
var stringReplaced = String.raw`c:\asd\flkj\klsd\ffjkl`.split('\\').join('/')
console.log(stringReplaced);
For replacing double backslash with single forward slash:
var stringReplaced = String.raw`c:\\asd\\flkj\\klsd\\ffjkl`.split('\\\\').join('/')
console.log(stringReplaced);
\ is a escape character. Therefore replaceableString does not contain any backslashes.
To fix this you should declare the string like this:
var replaceableString = "c:\\asd\\flkj\\klsd\\ffjkl";
First encode the string
then replace all occurrences of %5C with %5C%5C
At the end decode the string
var result = encodeURI(input);
result=decodeURI(result.replace(/%5C/g,"%5C%5C"));
If you have no control over the contents of the string you are trying to find backslashes in, and it contains SINGLE \ values (eg. variable myPath contains C:\Some\Folder\file.jpg), then you can actually reference the single backslashes in JavaScript as String.fromCharCode(92).
So to get the file name in my filepath example above.
var justTheName = myPath.split(String.fromCharCode(92)).pop();
In case of string matching, it is better to use encodeURIComponent, decodeURIComponent.
match(encodeURIComponent(inputString));
function match(input)
{
for(i=0; i<arr.length; i++)
{
if(arr[i] == decodeURIComponent(input))
return true;
else return false;
}
}
In the case of a single back slash in the string, the javascript replace method did not allow me to replace the single back slash.
Instead I had to use the split method which returns an array of the split strings and then concatenate the strings without the back slash (or whatever you want to replace it with)
Solution (replaced backslash with underscore):
var splitText = stringWithBackslash.split('\\');
var updatedText = splitText[0] + '_' + splitText[1];
You need to pass to pass value of a string through String.raw before you assign value to a variable.
var replaceableString = String.raw`c:\asd\flkj\klsd\ffjkl`.replace(/\\/g,"\\\\");
console.log(replaceableString)

I have a string and want to remove special chars in its specific part using javascript

I have a string looks like:
var myString= '{"key1":"value1", "key2":"value2", "key3":"value3"}';
What I want is to remove double qoutes and other special chars only from value3 ... for example some times we have string looks like:
var myString= '{"key1":"value1", "key2":"value2", "key3":"This is "value" with some special chars etc"}';
Please note I do not want to remove double quotes after colon and before This and similarly I do not want to remove last double quotes. I just want to modify string so it will become:
var myString = '{"key1":"value1", "key2":"value2", "key3":"This is value with some special chars etc"}';
Simple...
var myNewString = eval( '('+ myString +')');
var toBeEscaped = myNewString.key3;
var escapedString = doYourCleanUpStuff(toBeEscaped);
myNewString.key3 = escapedString;
myNewString = JSON.stringify(myNewString);
===============
What did I do?
1) Your string looks like valid JSON.
2) Cast it into JSON object. (using eval() )
3) Retrieve value of key3 and catch it in some temp variable.
4) Do cleanup things with this temporary variable.
5) assign cleaned up temporary variable back to key3.
6) Stringify the JSON.
Don't go around beating bush with array manipulation and split functions, especially when there are simpler ways :)
You will probably want to use the Array map function in conjunction with the string replace function.
To use the replace function, you'll probably want to use regular expressions. For example, the following regular expression will remove double quotes not immediately after a colon: [^:]".
To replace every quote not immediately followed by a colon in an array of strings, you could write this:
var myString= '{"key1":"value1", "key2":"value2", "key3":"value3"}';
var modified = myString.map(function(s) { return s.replace(/[^:]"/g, ''); });
Make your own modifications to the regular expression to match the characters you want to remove.
Refer to http://www.addedbytes.com/cheat-sheets/regular-expressions-cheat-sheet/.
First thing that comes to my mind is to isolate the Value you want.
You can .Split() for the value you want
var myString = '{"key1":"value1", "key2":"value2",
"key3":"value3"}';var n=str.split(" ");
var key3Value = str.split(//Based on your value);
//Run .replace() on your key3Value to replace your doublequotes, etc.
//Re-declare myString to include the updated key3Value
Sorry, no time at the moment to finish the code, and I am sure their are better/shorter answers than mine. Just wanted to include this as an option.

String manipulation using MooTools / JavaScript

How do I manipulate a string using MooTools / JavaScript
I would like to replace all after /p/ in following url:
http://example.com/groups/browse/catId/14/p/1000-1500
Expected result:
http://example.com/groups/browse/catId/14
That doesn't look like you want to replace, it looks like you want to remove.
You can do that with regular string operations in plain Javascript:
var s = "http://example.com/groups/browse/catId/14/p/1000-1500";
s = s.substr(0, s.indexOf("/p/")));
Simple enough with regex:
var url = "http://example.com/groups/browse/catId/14/p/1000-1500";
console.log(url.replace(/\/p\/.+/, ""));
//-> "http://example.com/groups/browse/catId/14"
In the regex above, \/p\/ is /p/ with escaped slashes, followed by .+ which means match any character (except white space) one or more times.
You can brush up on your JavaScript regular expressions at http://www.regular-expressions.info/javascript.html.
you don't have to use mootools necessarily. you can split the string with split function from javascript
var myString = 'http://example.com/groups/browse/catId/14/p/1000-1500';
newString = myString.split('/p/');
alert(newString[0]);

Javascript Replace text in string

I'm having some troubles getting regex to replace all occurances of a string within a string.
**What to replace:**
href="/newsroom
**Replace with this:**
href="http://intranet/newsroom
This isn't working:
str.replace(/href="/newsroom/g, 'href="http://intranet/newsroom"');
Any ideas?
EDIT
My code:
str = 'photo';
str = str.replace('/href="/newsroom/g', 'href="http://intranet/newsroom"');
document.write(str);
Thanks,
Tegan
Three things:
You need to assign the result back to the variable otherwise the result is simply discarded.
You need to escape the slash in the regular expression.
You don't want the final double-quote in the replacement string.
Try this instead:
str = str.replace(/href="\/newsroom/g, 'href="http://intranet/newsroom')
Result:
photo
You need to escape the forward slash, like so:
str.replace(/href="\/newsroom\/g, 'href=\"http://intranet/newsroom\"');
Note that I also escaped the quotes in your replacement argument.
This should work
str.replace(/href="\/newsroom/g, 'href=\"http://intranet/newsroom\"')
UPDATE:
This will replase only the given string:
str = 'photo';
str = str.replace(/\/newsroom/g, 'http://intranet/newsroom');
document.write(str);

Categories