replace single quote in middle of string using regex - javascript

Have a string:
stringName= "'john's example'"
Need to do a string.replace to remove the single quote in the middle of the string, not the first and last otherwise will break my javascript
have tried stringName.replace("/.'./","") to replace only the single quote in the middle of the string but does not work
Help is very appreciated! :)

Use (^'|'$)|' as matching regular expression:
stringName = "'john's e'xam'ple'";
console.log(
stringName.replace(/(^'|'$)|'/g, '$1')
);

First thing is you aren't doing a regex replace, you are replacing a string which looks like /.'./ (because of the " in the first argument). Secondly, the regex you're doing is only going to be looking for a single character (.) then a single quote, then another character. What you might want to do is something like stringName.replace(/(.+)'(.+)/, "$1$2")

Use split, join after stripping of first and last character
var f1 = (str) => str.charAt(0) + str.split("'").join("") + str.slice(-1);
f1( "'john's exa''mp'le'" ); //'johns example'

Related

RegEx for matching two single quotes from start and end of strings

I need to replace two quotes at the beginning and end of elements with one quote.
My code is:
const regex = /['']/g;
let categories = [];
let categoryArray = data.categories.split(','); // ''modiles2'', ''Men''s Apparel'', ''Women''s Apparel'', ''Jeans'', ''Sneakers''
for (let value of Object.values(categoryArray)) {
categories.push(categoryArray[i].replace(regex, '\''));
}
}
return categories
// What should be 'modiles2','Men''s Apparel','Women''s Apparel','Jeans','Sneakers'
// What comes back ''modiles2'',''Men''s Apparel'',''Women''s Apparel'',''Jeans'',''Sneakers''
My regular expression replaces only the first of two quotation marks with one quotation mark.
How do I solve this problem?
You need to match two quotation marks - use this regex:
const regex = /^'.*'$/g;
Character classes look for any single character between the brackets. Character classes that have duplicate characters, like [''], can do without such duplication.
"''modiles2'',''Men''s Apparel'',''Women''s Apparel'',''Jeans'',''Sneakers''"
.split(',')
.forEach(s => console.log( s.replace(/^''|''$/g, '\'') ))
This RegEx might help to do so. You might consider using \x27 instead of ' just to be safe.
^(\x27{2,})(.+)(\x27{2,})$
This RegEx creates three groups, just to be simple, and you might use $2, which is your target output.
Your pattern uses a character class [''] which matches any of the listed which could be written as ['] which is just '
If there can be more than 2 at the start or at the end, you could also use a quantifier {2,} to match 2 or more single quotes and replace with a single quote. To match exactly 2 single quotes use ''.
^'{2,}|'{2,}$
^'{2,} Match 2 or more quotes at the start of the string
| Or
'{2,}$ Match 2 or more single quotes at the end of the string
Regex demo
Use the /g global flag to replace all occurrences.
console.log("''modiles2'',''Men''s Apparel'',''Women''s Apparel'',''Jeans'',''Sneakers''"
.split(',')
.map(s => s.replace(/^'{2,}|'{2,}$/g, "'")))
Here is my two cents, in one line:
return data.categories.split(',').map(val => val.trim().replace(/^'{2,}|'{2,}$/, "'"));

javascript replace all occurrences ",\S" with ", \S"

I want to have spaces separating items in a CSV string. That is "123,456,789" => "123, 456, 789". I have tried, but been unable to construct a regexp to do this. I read some postings and thought this would to the trick, but no dice.
text = text.replace(new RegExp(",\S", "g"), ", ");
Could anyone show me what I am doing wrong?
You have two problems:
Backslashes are a pain in the, um, backslash; because they have so many meanings (e.g. to let you put a quote-mark inside a string), you often end up needing to escape the backslash with another backslash, so you need ",\\S" instead of just ",\S".
The \S matches a character other than whitespace, so that character gets removed and replaced along with the comma. The easiest way to deal with that is to "capture" it (by putting it in parentheses), and put it back in again in the replacement (with $1).
So what you end up with is this:
text = text.replace(new RegExp(',(\\S)', "g"), ", $1");
However, there is a slightly neater way of writing this, because JavaScript lets you write a regex without having a string, by putting it between slashes. Conveniently, this doesn't need the backslash to be escaped, so this much shorter version works just as well:
text = text.replace(/,(\S)/g, ", $1");
As an alternative to capturing, you can use a "zero-width lookahead", which in this situation basically means "this bit has to be in the string, but don't count it as part of the match I'm replacing". To do that, you use (?=something); in this case, it's the \S that you want to "look ahead to", so it would be (?=\S), giving us this version:
text = text.replace(/,(?=\S)/g, ", ");
There are 2 mistakes in your code:
\S in a string literal translates to just S, because \S is not a valid escape sequence. As such, your regex becomes /,S/g, which doesn't match anything in your example. You can escape the backslash (",\\S") or use a regex literal (/,\S/g).
After this correction, you will replace the character following the comma with a space. For instance, 123,456,789 becomes 123, 56, 89. There are two ways to fix this:
Capture the non-space character and use it in the replacement expression:
text = text.replace(/,(\S)/g, ', $1')
Use a negative lookahead assertion (note: this also matches a comma at the end of the string):
text = text.replace(/,(?!\s)/g, ', ')
text = text.replace(/,(\S)/g, ', $1');
try this:
var x = "123,456,789";
x = x.replace(new RegExp (",", "gi"), ", ");

How to replace last matched character in string using javascript

i want to replace last input character from keyboard to ''
My String Input are
sample string
"<p><strong>abscd sample text</strong></p>"
"<p>abscd sample text!</p>"
My last character is dynamic that can be any thing between
a to z, A to Z, 0 to 9, any special characters([~ / < > & ( . ] ).
So i need to replace just that character
for example in Sample 1 i need to replace "t" and in sample 2 in need to replace "!"
I tried below code. but it id not worked for me
var replace = '/'+somechar+'$/';
Any way to do it?
Step one
to replace the a character in a string, use replace() function of javaScript. Here is the MDN specification:
Returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match.
Step two
you need to location the character to be replaced through regular expression. You want to replace the last character of a string and this could be expressed as /(.+)(.)$/. . stands for any character, + means more than one character. Here (.+) matches all the character before the last one. (.) matches the last character.
What you want to replace is the one inside the second brackets. Thus you use the same string matched in the first bracket with $1 and replace whatever after it.
Here is the code to realize your intention:
text = 'abscd sample text';
text.replace(/(.+)(.)$/, '$1!');
Do you really need to use regular expressions? How about str = str.slice(0, -1); ? This will remove the last character.
If you need to replace a specific character, do it like this:
var replace = new RegExp(somechar + '$');
str = str.replace(replace, '');
You cannot use slashes in a string to construct a RegEx. This is different from PHP, for example.
I dont really understand which character you want to replace to what, but i think, you should use replace() function in JS: http://w3schools.com/jsref/jsref_replace.asp
string.replace(regexp/substr,newstring)
This means all keyboard character:
[\t\n ./<>?;:"'`!##$%^&*()[]{}_+=-|\\]
And this way you can replace all keyboard character before < mark to ""
string.replace("[a-zA-Z0-9\t\n ./<>?;:"'`!##$%^&*()[]{}_+=-|\\]<","<")

jQuery - Replace all parentheses in a string

I tried this:
mystring= mystring.replace(/"/g, "").replace(/'/g, "").replace("(", "").replace(")", "");
It works for all double and single quotes but for parentheses, this only replaces the first parenthesis in the string.
How can I make it work to replace all parentheses in the string using JavaScript? Or replace all special characters in a string?
Try the following:
mystring= mystring.replace(/"/g, "").replace(/'/g, "").replace(/\(|\)/g, "");
A little bit of REGEX to grab those pesky parentheses.
You should use something more like this:
mystring = mystring.replace(/["'()]/g,"");
The reason it wasn't working for the others is because you forgot the "global" argument (g)
note that [...] is a character class. anything between those brackets is replaced.
You should be able to do this in a single replace statement.
mystring = mystring.replace(/["'\(\)]/g, "");
If you're trying to replace all special characters you might want to use a pattern like this.
mystring = mystring.replace(/\W/g, "");
Which will replace any non-word character.
You can also use a regular experession if you're looking for parenthesis, you just need to escape them.
mystring = mystring.replace(/\(|\)/g, '');
This will remove all ( and ) in the entire string.
Just one replace will do:
"\"a(b)c'd{e}f[g]".replace(/[\(\)\[\]{}'"]/g,"")
That should work :
mystring= mystring.replace(/"/g, "").replace(/'/g, "").replace(/\(/g, "").replace(/\)/g, "");
That's because to replace multiple occurrences you must use a regex as the search string where you are using a string literal. As you have found searching by strings will only replace the first occurrence.
The string-based replace method will not replace globally. As such, you probably want to use the regex-based replacing method. It should be noted:
You need to escape ( and ) as they are used for group matching:
mystring= mystring.replace(/"/g, "").replace(/'/g, "").replace(/\(/g, "").replace(/\)/g, "");
This can solve the problem:
myString = myString.replace(/\"|\'|\(|\)/)
Example

Replacing second part of string with Javascript and replace()

I need to replace any occurrence of a sequence of integers followed by a dash and then another sequence of integers, with only the first sequence of integers. For example:
THIS IS A STRING 2387263-1111 STRING CONTINUES
Will become:
THIS IS A STRING 2387263 STRING CONTINUES
Can I use that with Javascript and replace()?
You can do:
str = str.replace(/(\d+)-\d+/,'$1');
See it
Which replaces a group of digits followed by a hyphen followed by a group of digits with the first group of digits.
If you want to replace multiple occurrences of such pattern just use the g modifier as:
str = str.replace(/(\d+)-\d+/g,'$1');
NEW ANSWER -
Yes, in your case according to me, first you need to match that whole string "2387263-1111" using a regex and then remove that part followed by '-' and then replace the result in the original string.
Check the answer from codaddict. Mine would've almost been same but his answer seems more appropriate.
OLD ANSWER: -
Why replace? Just use split and get the first value.
var str = "2387263-1111";
var output = str.split("-")[0];
User RegExp function of javascript
str = str.replace(new RegExp("-[0-9]+"), " ");
Not really a new answer, just an addition to codaddict. Don't know JScript's regex
all that well, but I asume it uses extended regular expressions (if not, forget this).
If you need validation on boundry conditions you could do something like this:
str = str.replace( /((^|\s)\d+)-\d+(?=\s|$)/g, '$1' );
That would prevent matching this type of thing:
A STRING 2387263-1111STRING CONTINUES
A STRING2387263-1111 STRING CONTINUES
A STRING2387263-1111STRING CONTINUES

Categories

Resources