How to replace a string containing sqare brackets in javascript? [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
how do you replace a string value with another in JavaScript ?
I have a string that contains a lot of this substring- Items[0]. How do I replace all of this to Items[1], taking into account that '0' is a dynamic value that I get from a variable.
I have used the replace method, and tried some 'RegExp' but couldn't do that. I think its because of those square brackets:
str.replace(new RegExp("Items[" + j + "]", "g"), "Items[" + (j - 1) +"]"));
Any help is appreciated. Thanks :)

You use new RegExp to create the regular expression. In the regex, you have to use \ to escape the [ because otherwise it has a special meaning. Since you're going to have to use a string to create the regex (since you need to include the value of your variable), you also have to escape the \ in the string, so we end up with two:
var variable = 0;
var rex = new RegExp("\\[" + variable + "]", "g");
var str = "This has Item[0] in more than one Item[0] place.";
var str = str.replace(rex, "Item[" + (variable + 1) + "]");
// If you want a dynamic replacement ^^^^^^^^^^^^^^^^^^^
// In this case, I used the value plus one.
console.log(str);
The "g" is a flag meaning "global" (throughout the string, not just the first occurrence).

Related

Find and replace # mentions using Javascript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I'm trying to parse strings to find and replace # mentions.
Here is a sample string:
Hi #jordan123 and #jordan have a good day
I want to find and replace #jordan with #jordananderson without modifying #jordan123
I used this regex to find a list of all of the mentions in the string:
let string = 'Hi #jordan123 and #jordan have a good day'
let result = string.match(/\B\#\w\w+\b/g);
that returns:
['#jordan123', '#jordan']
But I can't figure out how to continue and complete the replacement.
Valid characters for the username are alphanumeric and always start with the # symbol.
So it also needs to work for strings like this:
Hi #jordan123 and #jordan!! have a good day
And this
Hi #jordan123! and !#jordan/|:!! have a good day
My goal is to write a function like this:
replaceUsername(string, oldUsername, newUsername)
If I understand your question correctly, you need \b, which matches a word boundary:
The regex: #jordan\b will match:
Hi #jordan123 and #jordan!! have a good day
Hi #jordan123! and !#jordan/|:!! have a good day
To build this regex, just build it like a string; don't forget to sanitize the input if it's from the user.
var reg = new RegExp("#" + toReplace + "\\b")
In general if you have one string of a found value, and a larger string with many values, including the found value, you can use methods such as split, replace, indexOf and substring etc to replace it
The problem here is how to replace only the string that doesn't have other things after it
To do this we can first look for indexOf the intended search string, add the length of the string, then check if the character after it doesn't match a certain set of characters, in which case we set the original string to the substring of the original up until the intended index, then plus the new string, then plus the substring of the original string starting from the length of the search string, to the end. And if the character after the search string DOES match the standard set of characters, do nothing
So let's try to make a function that does that
function replaceSpecial(original, search, other, charList) {
var index= original.indexOf(search)
if(index > -1) {
var charAfter = original [index + search.length]
if (!charList.includes(charAfter)) {
return original. substring (0, index) + other + original. substring (index+ search.length)
} else return original
} else return original
}
Then to use it with our example
var main ="Hi #jordan123 and #jordan!! have a good day"
var replaced = replaceSpecial (main, "#jordan", "#JordanAnderson", [0,1,2,3,4,5,6,7,8,9])

Replace an expression in string using javascript [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have a string that has some numbers in the middle of the string.
For example,
var str = "abcd-123456.com"
I want to remove the numbers like this
abcd.com
I am not trying to replace all numbers.
I have to replace only -*. expression with "".
How do I do this in JavaScript?
var str = "abcd-123456.com"
str = str.replace(/-[0-9]*/g, '')
Your comments lead me to believe you want
var str = "abcd-123456.com";
var str1 = str.substring(0,str.indexOf("-"))+str.substring(str.indexOf("."))
console.log(str1);
//or with regex
// dasah plus 6 digits to nothing
var str2 = str.replace(/-\d{6}/,"")
console.log(str2);
// dash, digits and an dot to dot
var str3 = str.replace(/-\d+\./,".")
console.log(str3);
AS PER YOUR COMMENT
The answer of Shivaji Varma will nearly do the tricks.
var str = "abc5d-123456.c0om"
str = str.replace(/-[0-9]*./g, "")
console.log(str)
Soooo,
Using the slash indicate a regular expression.
[0-9] indicate you want to replace all digit between 0 and 9 (included)
"*" to remove all digits
"-" and "." to delimite

How can I escape a ';' in Javascript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I am trying to write an algorithm where I replace characters like &, <, >, , ', " with their HTML entity counterpart(i.e. & would be replaced with &. This requires me to put a semi-colon in a string, which creates an error because Javascript thinks that I have ended the line. Here is my code:
str.charAt(i) = '&';
I thought that I could cancel it like so:
str.charAt(i) = '&amp\;';
but this creates an error.
The problem is that your assignment is invalid. You seem to be trying to mutate a string, which is impossible in JS since strings are immutable.
Instead you need to create a new string with the parts you want replaced with the new content.
var new_str = s.replace(/(?:(&)|(<)|(>)|(')|("))/g, function(s, g1,g2,g3,g4,g5) {
if (g1) return "&"
if (g2) return "<"
if (g3) return ">"
if (g4) return "&apos;"
if (g5) return """
});
Semi-colons inside string literals do not terminate statements in JavaScript.
ReferenceError: Invalid left-hand side in assignment
Your problem is that you are trying to assign a value to the return value of a function, which isn't allowed.
If you want to replace characters in a string, use the replace method.
In this case, you are trying to convert a string of text into a string of HTML and it is simpler to let the DOM do that for you:
var div_node = document.createElement('div');
var text_node = document.createTextNode(str);
div_node.appendChild(text_node);
var str_html = div_node.innerHTML;
Note that this won't replace all of the characters. Some don't need escaping all the time.
You don't need to escape semicolons inside strings. JavaScript doesn't think the line has ended in a string any more than it thinks the line ended inside for (var i = 0; ...).
The problem isn't an escaping issue. It's that you're attempting to assign a value to the static output of the String.charAt() method, which is not allowed.
Instead, try using the string replace method to replace your HTML entities with alternative values.
s = 'Hello & World';
s.replace(/\&/g, '&');
You can use a function to replace characters by their HTML entities:
function htmlEntities(str) {
return String(str)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, '&apos;');
}
; don't need any replacement.

Replace in comma followed by double quotes in javascript [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
Can anyone tell me how to replace comma followed by double quotes(",) with double quotes(") in java script
Actually I am getting the string as ",4,34,26,23"
but I want to remove the first comma in the string
also the same when it occurs at the last(,") as below
"4,34,23,54,"
Thanks in Advance
Rakesh
You can use regular expressions like this
var data = ",4,34,26,23,";
data = data.replace(/^,|,$/g, "");
console.log(data);
Output
4,34,26,23
If the double quotes are also part of the original string,
var data = "\",4,34,26,23,\"";
data = data.replace(/^",|,"$/g, "");
If you want to strip only the , and retain ", you can just put the double quotes as the second parameter to the replace, as suggested by #nnnnnn, like this
data = data.replace(/^,|,$/g, "\"");
data = data.replace(/^",|,"$/g, "\"");
var a = ",4,34,26,23";
var replaced=a.replace(',','');
alert(replaced);
Try this
var x = ',4,34,26,23';
x.replace(/^,|,$/g,'');
This removes any starting or ending commas :
",4,34,26,23,".replace(/^,|,$/g,"") // "4,34,26,23"
try this
var str = '",4,34,26,23"';
str = str.replace('",','"');

How to insert character after second characters in string? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
How can I add a character after the second characters in string?
Ex: I want this : 1700 to become this: 17:00.
The simplest way, in my opinion, is using substr to split the string and concatenate the other character in between. This will work no matter the length of the second part:
var str = "1700";
str.substr(0,2)+":"+str.substr(2);
this would do the magic:
"1700".replace(/(..)$/, ":$1")
alternative you can do something like look from behind in substr too like:
var string = "1700";
string = string.substr(0, string.length -2) + ":" + string.substr(-2, 2);
they both also work on something like: 900 wich will turn into 9:00
the regex and the substr line both do the same. if you want readability i'd consider the regex.
You could do this:
'1700'.match(/../g).join(':')
The following regexp accepts 3+ chars:
'700'.match(/^(.+)(..)$/).slice(1, 3).join(':') // "7:00"
Shortest and probably fastest solution:
s[0]+s[1]+":"+s[2]+s[3]
Without using regexp, you can use substr --
string = string.substr(0,2) + ":" + string.substr(2);
You can use substring. Consider the following:
string1 = "1700";
string2 = ":";
string1 = string1.substring(0,2) + string2 + string1.substring(2);
alert(string1);

Categories