This question already has answers here:
How do I replace all occurrences of a string in JavaScript?
(78 answers)
Closed 4 years ago.
Suppose we have a string: "Someone one one-way"
And I want to replace THE WORD "one" with THE WORD "two".
Note: I don't want "someone" or "one-way" to change.
I tried to use str.replace(/one/g , "two");
But the result was "Sometwo two two-way"
This is not the intended result...
I want to get "Someone two one-way"
ANY HELP WOULD BE APPRECIATED. THANKS IN ADVANCE....
You can validate the spaces too:
//var str = "Someone one one-way";
var str = "one one Someone one one-way one,one";
var replace='two';
//using lookahead and lookbehind
var result= str.replace(/(?<=[^a-zA-Z-]|^)one(?=[^a-zA-Z-]|$)/gm , "two");
console.log(result);
//result: two two Someone two one-way two,two
eval('STR.SPLIT(" ONE ").JOIN(" TWO ")'.toLowerCase())
try this regex:
\s(one)\s
you may add modify it for case sensitive.
let input = "Someone one one-way"
output = input.split(" ").map((item)=> item ==='one'? 'two' : item).join(" ");
console.log(output)
You can try this:
.replace(/\bone\b(?!-)/g , "two")
\b matches on a word boundary.
(?!-) is a negative lookahead because you do not want to replace one if followed by a dash. \b recognizes the dash as a word boundary.
There is another pitfall when you have something like "-one".
Use this if this is a Problem:
.replace(/[^-]\bone\b(?!-)/g , function(x){return x.substring(0,1) + 'two'})
Ideally you would use negative look ahead, but this is currently not supported by all Browsers.
Related
This question already has answers here:
Regular expression for a string containing one word but not another
(5 answers)
Closed 1 year ago.
I have some troubles with regex, until now, I had no problem except for the following one :
I have 2 strings, I want to match with one but not the second one which contains a specific word.
var text1 = "The sun is yellow and the sky is blue";
var text2 = "The sun is yellow and the clouds are white";
It's really basic for the example but my regex was like that before :
var regex = /sun/g;
So this was ok for the text1 BUT now I want to return false the match if the string contains "clouds"
So text1 would be TRUE but not text2
I tried with (?!clouds) but I'm probably doing it wrong. It's pretty hard to use regex at this level. So I hope you could help me.
Thank you
Something like this would do it:
^(?!.*\bclouds\b)(?=.*\bsun\b).*$
https://regex101.com/r/TYZHwS/1
This question already has answers here:
Regular Expression to get a string between parentheses in Javascript
(10 answers)
Closed 4 years ago.
How can I modify this string:
"SRID=4326;POINT (-21.93038619999993 64.1444948)"
so it will return
"-21.93038619999993 64.1444948"
(and then I can split that)?
The numbers in the string can be different.
I've tried using .replace & split, but I couldn't get it to work properly. How can I make this happen using Javascript?
You can try with match and regex:
"SRID=4326;POINT (-21.93038619999993 64.1444948)".match(/\(([^)]+)\)/)[1]
// "-21.93038619999993 64.1444948"
I am not good using REGEXP but this could be a solution with pure split.
Hope it helps :>
var str = "SRID=4326;POINT (-21.93038619999993 64.1444948)" ;
var newStr = str.split('(')[1].split(')')[0];
console.log(newStr)
var new_string = string.replace("SRID=4326;POINT (", "");
You can use a regular expression. The first number is put in first, the second number is put in second.
const INPUT = "SRID=4326;POINT (-21.93038619999993 64.1444948)";
const REGEX = /SRID=\d+;POINT \((.+) (.+)\)/
const [_, first, second] = INPUT.match(REGEX);
console.log(first);
console.log(second);
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to ignore acute accent in a javascript regex match?
I have some javascript as :
var myString = 'préposition_preposition';
var regex = new RegExp("epo", "ig");
alert(myString.match(regex));
is it possible to match "épo" and "epo", if I set in regex only epo (or only épo)?
I had the same problem recently. Regex operates with ascii, therefor special characters like é or ß are not recognized. You need to explicitely include those into your regex.
Use this:
var regex = /[ée]po/gi;
Hint: Don't use new Regex() it's rather slow, but declare the regex directly instead. This also solves some quoting/escaping issues.
No you can not achieve this behavior. RegEx match exactly the string you provided. How should the computer know when épo or epo is what you are looking for!
But you can specify a class of chracters that can be matched new RegExp("[eé]po", "ig");
Try this:
var str = 'préposition_preposition';
str.match(/(e|é)po/gi);
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JavaScript Split without losing character
I have a string:
"<foo>abcdefg</bar><foo>abcdefg</bar><foo>abcdefg</bar><foo>abcdefg</bar>"
I want to separate all instances of "abcdefg" into an array like this:
["<foo>abcdefg</bar>", "<foo>abcdefg</bar>", "<foo>abcdefg</bar>", "<foo>abcdefg</bar>"];
I try:
var str="<foo>abcdefg</bar><foo>abcdefg</bar><foo>abcdefg</bar><foo>abcdefg</bar>";
var Array_Of_FooBars = str.split("</bar>");
alert(Array_Of_FooBars);
But it returns:
["<foo>abcdefg", "<foo>abcdefg", "<foo>abcdefg", "<foo>abcdefg",]
It is removing the separator ''. I don't want that.
How can I use split and not lose the separators from the string?
Thanks.
Ken
Try this. It's not a perfect solution, but it should work in most cases.
str.split(/(?=<foo>)/)
That is, split it in the position before each opening tag.
EDIT: You could also do it with match(), like so:
str.match(/<foo>.*?<\/bar>/g)
It seems that you would most likely want to use match:
var s = "<foo>abcd1efg</bar><foo>abc2defg</bar><foo>abc3defg</bar><foo>abc4defg</bar>"
s.match(/(<foo>.+?<\/bar>)/g)
// =>["<foo>abcd1efg</bar>", "<foo>abc2defg</bar>", "<foo>abc3defg</bar>", "<foo>abc4defg</bar>"]
You could just iterate over a simple regular expression and build the array that way:
var x = new RegExp('<foo>(.*?)</bar>', 'ig'),
s = "<foo>abcdefg</bar><foo>abcdefg</bar><foo>abcdefg</bar><foo>abcdefg</bar>",
matches = [];
while (i = x.exec(s)) {
matches.push(i[0]);
}
Just realized using String.match() would be better; this code would be more useful for matching the contents inside the tags.
Use positive lookahead so that the regular expression asserts that the special character exists, but does not actually match it:
string.split(/<br \/>(?=&#?[a-zA-Z0-9]+;)/g);
have a regex problem :(
what i would like to do is to find out the contents between two or more numbers.
var string = "90+*-+80-+/*70"
im trying to edit the symbols in between so it only shows up the last symbol and not the ones before it. so trying to get the above variable to be turned into 90+80*70. although this is just an example i have no idea how to do this. the length of the numbers, how many "sets" of numbers and the length of the symbols in between could be anything.
many thanks,
Steve,
The trick is in matching '90+-+' and '80-+/' seperately, and selecting only the number and the last constant.
The expression for finding the a number followed by 1 or more non-numbers would be
\d+[^\d]+
To select the number and the last non-number, add parens:
(\d+)[^\d]*([^\d])
Finally add a /g to repeat the procedure for each match, and replace it with the 2 matched groups for each match:
js> '90+*-+80-+/*70'.replace(/(\d+)[^\d]*([^\d])/g, '$1$2');
90+80*70
js>
Or you can use lookahead assertion and simply remove all non-numerical characters which are not last: "90+*-+80-+/*70".replace(/[^0-9]+(?=[^0-9])/g,'');
You can use a regular expression to match the non-digits and a callback function to process the match and decide what to replace:
var test = "90+*-+80-+/*70";
var out = test.replace(/[^\d]+/g, function(str) {
return(str.substr(-1));
})
alert(out);
See it work here: http://jsfiddle.net/jfriend00/Tncya/
This works by using a regular expression to match sequences of non-digits and then replacing that sequence of non-digits with the last character in the matched sequence.
i would use this tutorial, first, then review this for javascript-specific regex questions.
This should do it -
var string = "90+*-+80-+/*70"
var result = '';
var arr = string.split(/(\d+)/)
for (i = 0; i < arr.length; i++) {
if (!isNaN(arr[i])) result = result + arr[i];
else result = result + arr[i].slice(arr[i].length - 1, arr[i].length);
}
alert(result);
Working demo - http://jsfiddle.net/ipr101/SA2pR/
Similar to #Arnout Engelen
var string = "90+*-+80-+/*70";
string = string.replace(/(\d+)[^\d]*([^\d])(?=\d+)/g, '$1$2');
This was my first thinking of how the RegEx should perform, it also looks ahead to make sure the non-digit pattern is followed by another digit, which is what the question asked for (between two numbers)
Similar to #jfriend00
var string = "90+*-+80-+/*70";
string = string.replace( /(\d+?)([^\d]+?)(?=\d+)/g
, function(){
return arguments[1] + arguments[2].substr(-1);
});
Instead of only matching on non-digits, it matches on non-digits between two numbers, which is what the question asked
Why would this be any better?
If your equation was embedded in a paragraph or string of text. Like:
This is a test where I want to clean up something like 90+*-+80-+/*70 and don't want to scrap the whole paragraph.
Result (Expected) :
This is a test where I want to clean up something like 90+80*70 and don't want to scrap the whole paragraph.
Why would this not be any better?
There is more pattern matching, which makes it theoretically slower (negligible)
It would fail if your paragraph had embedded numbers. Like:
This is a paragraph where Sally bought 4 eggs from the supermarket, but only 3 of them made it back in one piece.
Result (Unexpected):
This is a paragraph where Sally bought 4 3 of them made it back in one piece.