I have the following string:
[27564][85938][457438][273][48232]
I want to replace all the [ with ''. I tried the following but it didn't work:
var str = '[27564][85938][457438][273][48232]'
var nChar = '[';
var re = new RegExp(nChar, 'g')
var visList = str.replace(re,'');
what am I doing wrong here?
Many thanks in advance.
You need to escape the [ otherwise it is interpreted as the start of a character class:
var nChar = '\\[';
If nChar is a variable (and I assume it is otherwise there would be little point in using RegExp instead of /.../g) then you may find this question useful:
Is there a RegExp.escape function in Javascript?
var string = "[27564][85938][457438][273][48232]";
alert(string.replace(/\[/g, '')); //outputs 27564]85938]457438]273]48232]
I escaped the [ character and used a global flag to replace all instances of the character.
I met this problem today.
The requirement is replace all "c++" in user input string. Because "+" has meaning in Reg expression, string.replace fails.
So I wrote a multi-replace function for js string. Hope this can help.
String.prototype.mreplace = function (o, n) {
var off = 0;
var start = 0;
var ret = "";
while(true){
off = this.indexOf(o, start);
if (off < 0)
{
ret += this.substring(start, this.length);
break;
}
ret += this.substring(start, off) + n;
start = off + o.length;
}
return ret;
}
Example:
"ababc".mreplace("a", "a--"); // returns "a--ba--bc"
Related
I've been dealing with an algorithm which takes a sequence of letters in alphabetic order, and if there is a character missing, it returns that character.
For example: fearNotLetter("abcdfg") would return "e".
My questions are:
What is the logic behind this solution?
Why and how regex is used here?
How does the condition in the for loop work?
function fearNotLetter(str) {
var allChars = '';
var notChars = new RegExp('[^'+str+']','g');
for (var i = 0; allChars[allChars.length-1] !== str[str.length-1] ; i++)
allChars += String.fromCharCode(str[0].charCodeAt(0) + i);
return allChars.match(notChars) ? allChars.match(notChars).join('') : undefined;
}
function fearNotLetter(str) {
var allChars = '';
var notChars = new RegExp('[^'+str+']','g'); //1
for (var i = 0; allChars[allChars.length-1] !== str[str.length-1] ; i++)//2
allChars += String.fromCharCode(str[0].charCodeAt(0) + i);
return allChars.match(notChars) ? allChars.match(notChars).join('') : undefined; //3
}
As the variable name says, it creates a negate of str which means
like !abcdfg
Loop, build the full correct string until the last
character of str, means full letters of the alphabet untill character g => abcdefg
Then it compares with match method of string the full text with the provided text:
dummy way you can think
abcdefg - abcdfg then you get e, if there are multiple characters are missing it concatenates with join method.
I'm working to update this function which currently takes the content and replaces any instance of the target with the substitute.
var content = textArea.value; //should be in string form
var target = targetTextArea.value;
var substitute = substituteTextArea.value;
var expression = new RegExp(target, "g"); //In order to do a global replace(replace more than once) we have to use a regex
content = content.replace(expression, substitute);
textArea.value = content.split(",");
This code somewhat works... given the input "12,34,23,13,22,1,17" and told to replace "1" with "99" the output would be "992,34,23,993,22,99,997" when it should be "12,34,23,13,22,99,17". The replace should only be performed when the substitute is equal to the number, not a substring of the number.
I dont understand the comment about the regex needed to do a global replace, I'm not sure if that's a clue?
It's also worth mentioning that I'm dealing with a string separated by either commas or spaces.
Thanks!
You could do this if regex is not a requirement
var str = "12,34,23,13,22,1,17";
var strArray = str.split(",");
for(var item in strArray)
{
if(strArray[item] === "1")
{
strArray[item] = "99"
}
}
var finalStr = strArray.join()
finalStr will be "12,34,23,13,22,99,17"
Try with this
var string1 = "12,34,23,13,22,1,17";
var pattern = /1[^\d]/g;
// or pattern = new RegExp(target+'[^\\d]', 'g');
var value = substitute+",";//Replace comma with space if u uses space in between
string1 = string1.replace(pattern, value);
console.log(string1);
Try this
target = target.replace(/,1,/g, ',99,');
Documentation
EDIT: When you say: "a string separated by either commas or spaces"
Do you mean either a string with all commas, or a string with all spaces?
Or do you have 1 string with both commas and spaces?
My answer has no regex, nothing fancy ...
But it looks like you haven't got an answer that works yet
<div id="log"></div>
<script>
var myString = "12,34,23,13,22,1,17";
var myString2 = "12 34 23 13 22 1 17";
document.getElementById('log').innerHTML += '<br/>with commas: ' + replaceItem(myString, 1, 99);
document.getElementById('log').innerHTML += '<br/>with spaces: ' + replaceItem(myString2, 1, 99);
function replaceItem(string, needle, replace_by) {
var deliminator = ',';
// split the string into an array of items
var items = string.split(',');
// >> I'm dealing with a string separated by either commas or spaces
// so if split had no effect (no commas found), we try again with spaces
if(! (items.length > 1)) {
deliminator = ' ';
items = string.split(' ');
}
for(var i=0; i<items.length; i++) {
if(items[i] == needle) {
items[i] = replace_by;
}
}
return items.join(deliminator);
}
</script>
I have some strings like:
str1 = "Point[A,B]"
str2 = "Segment[A,B]"
str3 = "Circle[C,D]"
str4 = "Point[Q,L]"
Now I want to have function that gives me character after "[" and the character before "]". How could I make something like that ?
try this one...
var str = "Point[A,B]";
var start_pos = str.indexOf('[') + 1;
var end_pos = str.indexOf(']',start_pos);
var text_to_get = str.substring(start_pos,end_pos)
alert(text_to_get);
You'd need regex to do that
var matches = /\[(.*?)\]/.exec(str1);
alert(matches[1]);
You can use match() to extract the characters:
str.match(/\[(.*)\]/)[1]
A safer way would be:
var matches = str.match(/\[(.*)\]/);
if(matches) {
var chars = matches[1];
}
Here's an approach which avoids regex.
var str = "Point[A,B]";
var afterOpenBracket = str.split("[")[1]; // returns "A,B]"
var bracketContents = afterOpenBracket.split("]")[0]; // returns "A,B"
There, pretty simple! bracketContents now contains the entirety of the text between the first set of brackets.
We can stop here, but I'll go a step further anyway and split up the parameters.
var parameters = bracketContents.split(","); // returns ["A", "B"]
Or in case u have more [A,C,D,B] and don't want to use regex:
var str1 = "Point[A,C,D,B]";
function extract(str1){
var a = str1.charAt(str1.indexOf('[')+1);
var b = str1.charAt(str1.indexOf(']')-1);
return [a, b];
//or
//a.concat(b); //to get a string with that values
}
console.log(extract(str1));
I use this regex
str = "asd34rgr888gfd98";
var p = str.match(/\d{2}/);
alert(p[0]);
butI not understood how can use variable as quantificator, that is how write this:
var number = 2;
var p = str.match(/\d{number}/);
P.S. I see this page JavaScript regex pattern concatenate with variable
but not understood how use example from these posts, in my case.
You need to build your regex as a string and pass it to the RegExp constructor:
var regexString = '\\d{' + number + '}';
var regex = new RegExp(regexString);
var p = str.match(regex);
Notice that when building a regex via a string, you need to add some extra escape characters to escape the string as well as the regex.
var number = "2"
var p = new RegExp("\\d{" + number + "}");
This should work:
var str = "asd34rgr888gfd98";
number = 3;
p = str.match(new RegExp('\\d{' + number + '}'));
alert(p[0]);
I would like to replace every other comma in a string with a semicolon.
For example:
1,2,3,4,5,6,7,8,9,10
would become
1;2,3;4,5;6,7;8,9;10
What would be the regexp to do this? An explanation would be great.
Thank you :)
var myNums = "1,2,3,4,5,6,7,8,9,10";
myNums.replace(/(.*?),(.*?,)?/g,"$1;$2");
That'll do it.
var str = '1,2,3,4,5,6,7,8,9,10';
str.replace(/,(.*?,)?/g, ';$1');
// Now str === "1;2,3;4,5;6,7;8,9;10"
You would do something like this:
myString.replace(/,/g, ';');
You could use this regex pattern
([^,]*),([^,]*),?
And replace with $1;$2,. The question mark on the end is to account for the lack of a comma signaling the end of the last pair.
For example...
var theString = "1,2,3,4,5,6,7,8,9,10";
theString = theString.replace(/([^,]*),([^,]*),?/ig, "$1;$2,"); //returns "1;2,3;4,5;6,7;8,9;10,"
theString = theString.substring(0, theString.length - 1); //returns "1;2,3;4,5;6,7;8,9;10"
A non-regex answer:
function alternateDelims(array, delim_one, delim_two) {
var delim = delim_one,
len = array.length,
result = [];
for(var i = 0; i < len; i += 1) {
result.push(array[i]);
if(i < len-1) { result.push(delim); }
delim = (delim === delim_one) ? delim_two : delim_one;
}
return result.join('');
}
nums = "1,2,3,4,5,6,7,8,9,10"
alternateDelims(nums.split(','), ';', ',');