Regex to change quoting style - javascript

In the text that I get, I want to replace all the dialogue quotes with double quotes, while keeping the single quotes used in contractions like "aren’t". I want to use a String.replace() with a regular expression to do this..
E:g:
var text = "'I'm the cook,' he said, 'it's my job.'";
console.log(text.replace(/*regEx*/, "\""));
//should return → "I'm the cook," he said, "it's my job."
Now I know a regex that works for me, at least for the example text.
console.log(text.replace(/\B'/g, "\""));
However, I wonder if there is any other regex I can use to accomplish this. Just curious.

I noticed that the regular expression you provided doesn't replace single quotes in the beginning of the string. I came up with this one instead:
var str = "'Hello', - she said\n'Hi!' - he whispered\n";
console.log(str.replace(/\B'|'\B/g, "\""));

Related

Rewriting javascript regex in php when regex have escapes

I'm trying to write my regex as string (it's part of my S-Expression tokenizer that first split on string, regular expressions and lisp comments and then tokenize stuff between), it works in https://regex101.com/r/nH4kN6/1/ but have problem to write it as string for php.
My JavaScript regex look like this:
var pre_parse_re = /("(?:\\[\S\s]|[^"])*"|\/(?! )[^\/\\]*(?:\\[\S\s][^\/\\]*)*\/[gimy]*(?=\s|\(|\)|$)|;.*)/g;
I've tried to write this regex in php (the one from Regex101 was inside single quote).
$pre_parse_re = "%(\"(?:\\[\\S\\s]|[^\"])*\"|/(?! )[^/\\]*(?:\\[\\S\\s][^/\\]*)*/[gimy]*(?=\\s|\\(|\\)|$)|;.*)%";
My input
'(";()" /;;;/g baz); (baz quux)'
when called:
$parts = preg_split($pre_parse_re, $str, -1,
PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
it should create same array as in Regex101 (3 matches and stuff between) but it keep splitting on first semicolon inside regex /;;;/g
I think your escaping might be incorrect. Try this regex instead:
$pre_parse_re = "%(\"(?:\\\\[\\\\S\\\\s]|[^\"])*\"|\/(?! )[^\/\\\\]*(?:\\\\[\S\s][^\/\\\\]*)*\/[gimy]*(?=\s|\(|\)|$)|;.*)%";
Using preg_split might also return more than the capturing groups that you want, so you could also change to use this if you just want the 3 matches.
$parts;
preg_match_all($pre_parse_re, $str, $parts, PREG_SET_ORDER, 0);

Splitting string by {0}, {1}...{n} and replace with empty string

I have the following String:
var text = "Hello world! My name is {0}. How {1} can you be?"
I wanna find each of the {n} and replace them with an empty string. I'm totally useless with regex and tried this:
text = text.split("/^\{\d+\}$/").join("");
I'm sure this is an easy answer and probably exist some answer already on SO but I'm not sure what to search for. Not even sure what the "{" are called in english.
Please (if possible) maintain the use of "split" and "join".
Thanks!
You could achieve this through string.replace function.
string.replace(/\{\d+\}/g, "")
Example:
> var text = "Hello world! My name is {0}. How {1} can you be?"
undefined
> text.replace(/\{\d+\}/g, "")
'Hello world! My name is . How can you be?'
Through string.split. You just need to remove the anchors. ^ asserts that we are at the start and $ asserts that we are at the end. Because there isn't only a string {num} exists in a single line, your regex fails. And also remove the quotes which are around the regex delimiter /
> text.split(/\{\d+\}/).join("");
'Hello world! My name is . How can you be?'
You were close. What you want is: text = text.split(/\{\d+\}/).join("");
The two things that you missed were:
^ = the start of the string and $ = the end of the string. Since there are other characters around the pattern that you are trying to match, you don't want those.
if you are using a regular expression in the split() method, you need to use a RegExp object, not a string. Removing the "'s and just having the expression start and end with / will define a RegExp object.
I would actually agree with the others that the replace() method would be a better way to do what you are trying to accomplish, but if you want to use split() and join(), as you've stated, this is the change that you need.
You can just use replace mehthod:
var repl = text.replace(/\{\d+\} */g, '');
//=> "Hello world! My name is . How can you be?"

RegExp using regex + variables

I know there are many questions about variables in regex. Some of them for instance:
concat variable in regexp pattern
Variables in regexp
How to properly escape characters in regexp
Matching string using variable in regular expression with $ and ^
Unfortunately none of them explains in detail how to escape my RegExp.
Let's say I want to find all files that have this string before them:
file:///storage/sdcard0/
I tried this with regex:
(?:file:\/\/\/storage\/sdcard0\(.*))(?:\"|\')
which correctly got my image1.jpg and image2.jpg in certain json file. (tried with http://regex101.com/#javascript)
For the life of me I can't get this to work inside JS. I know you should use RegExp to solve this, but I'm having issues.
var findStr = "file:///storage/sdcard0/";
var regex = "(?:"+ findStr +"(.*))(?:\"|\')";
var re = new RegExp(regex,"g");
var result = <mySearchStringVariable>.match(re);
With this I get 1 result and it's wrong (bunch of text). I reckon I should escape this as said all over the web.. I tried to escape findStr with both functions below and the result was the same. So I thought OK I need to escape some chars inside regex also.
I tried to manually escape them and the result was no matches.
I tried to escape the whole regex variable before passing it to RegExp constructor and the result was the same: no matches.
function quote(regex) {
return regex.replace(/([()[{*+.$^\\|?])/g, '\\$1');
}
function escapeRegExp(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
What the hell am I doing wrong, please?
Is there any good documentation on how to write RegExp with variables in it?
All I needed to do was use LAZY instead of greedy with
var regex = "(?:"+ findStr +"(.*?))(?:\"|\')"; // added ? in (.*?)

Modifying a string by replacing

How can I replace some words in a string with some other words? For example:
var text1 = "This is a sentence. It is a pencil."
text2 = modify(text1);
I want text2 to be "That was a sentence. I was a pencil."
So modify function replaces This->That , is->was
To replace all instances of the substring is with was you can use the replace[MDN] method:
text2 = text1.replace(/is/g, "was");
Note that because is is a part of the word this, it will actually return
Thwas was a sentence
If you wanted to replace all instances of This to That and is to was, you could chain the calls to the replace method.
text2 = text1.replace(/This/g, "That").replace(/is/g, "was");
This will correctly do your replacement from
This is a sentence. It is a pencil.
to
That was a sentence. It was a pencil.
You can see this in action on jsFiddle.
Note that find and replace actions like this can always have unintended consequences. For example, this string
Thistles and thorns are bad for missiles and corns.
will turn into this one after your replacement:
Thatles and thorns are bad for mwassiles and corns.
This sort of thing is popularly known as the Clbuttic mistake.
text1 = text1.replace('is', 'was');
Btw, .replace accepts regular expressions as well
Utilize the javascript replace method -
http://www.w3schools.com/jsref/jsref_replace.asp
Note: To replace every occurrence of a string in JavaScript, you must provide the replace() method a regular expression with a global modifier as the first parameter.
You could use javascript's Replace function like this:
var text2 = text1.replace('is','was');

Finding a word and replacing using regular expressions in javascript

I need information about finding a word and replacing it with regular expressions in javascript.
You can use \b to specify a word boundary. Just put them around the word that you want to replace.
Example:
var s = "That's a car.";
s = /\ba\b/g.replace(s, "the");
The variable s now contains the string "That's the car". Notice that the "a" in "That's" and "car" are unaffected.
Since you haven't really asked a question, the best I can do is point you here:
http://www.w3schools.com/jsref/jsref_obj_regexp.asp
And tell you also that the replace method for a string is replace, as in:
var myStr = "there is a word in here";
var changedStr = myStr.replace(/word/g, "replacement");

Categories

Resources