Javascript Replace text in string - javascript

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);

Related

replace function to replace single quote string

I have this string something='http://example.com/something' and how can I replace the something=' with nothing?
when I do str.replace('something='','') I got syntax error. I tried str.replace('something=\'','') and expect to escape the single quote with slash, it doesn't work too.
str.replace('something='','') will of course lead to a syntax error.
Try
str.replace("something='","")
I believe what you are looking for is a replacement of something=' and all ticks (') including the closing one... So you could use this:
var str = "something='http://example.com/something'";
alert(str.replace(/something='(.*)'/, "$1"));
You need to update the str variable with the returned value since String#replace method doesn't update the variable.
str = str.replace('something=\'', '')
Although it's better to use double quotes instead of escaping.
str = str.replace("something='", '')

Match double quotes that doesn't have a preceding escape character

I have a string that has some double quotes escaped and some not escaped.
Like this,
var a = "abcd\\\"\""
a = a.replace(/\[^\\\]\"/g, 'bcde')
console.log(a)
The string translates to literal, abcd\"".
Now, i am using the above regex to replace non-escaped double quotes.
And only the second double quote must be replaced.
The result must look like this,
abcd\"bcde
But it is returing the same original string, abcd\"" with no replacement.
You can use capture group here:
a = a.replace(/(^|[^\\])"/g, '$1bcde')
//=> abcd\"bcde
A negative lookbehind is what you want. However it is not supported in the Regex' JS flavor.
You can achieve this by processing the result in two steps:
var a = "abcd\\\"\"";
console.log(a);
var result = a.replace(/(\\)?"/g, function($0,$1){ return $1?$0:'{REMOVED}';});
console.log(result);

JavaScript String.replace() all instances and escaping

I have a string: Dkjd(Dk39dD_2=3499(39482&#6293jd
I would like to escape all characters of my choosing (say, _#-) with a backslash. I'm confused how I would do this with String.replace. Can I use the original value in the new value var? Can I use RegEx to do this? Thanks.
No need to use function, use backreference:
source.replace(/([_#\-])/g, "\\$1")
The thing in parentheses can be referenced as $1 in replacement string.
This should be easy with a regex.
var str = 'Dkjd(Dk39dD_2=3499(39482&#6293jd';
str = str.replace(/[_#-]/g, function(match){
return '\\'+match;
});
console.log(str); // Dkjd(Dk39dD\_2=3499(39482&\#6293jd
Simply,
var str = 'Dkjd(Dk39dD_2=3499(39482&#6293jd';
str = str.replace(/([_#-])/g, '\\$1');
Hope it helps.

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)

Replace Characters from string with 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.

Categories