I have some values like 10++10--10+-10-+.my question is how to replace these value into matched value using single reg expression.i need a answer like 10+10-10-10-.
its means
'++'='+',
'--'='-',
'+-'='-',
'-+'='-';
.please help me for solve my problem.
Match and capture the alternatives you need to replace with a specific string, and then use the replace callback to see which group matched and replace accordingly:
var s = '10++10--10+-10-+';
document.body.innerHTML = s.replace(/(\+\+)|([-+]-|-\+)/g, function(m, g1, g2) {
return g1? "+" : "-";
});
The (\+\+)|([-+]-|-\+) regex contains 2 alternative groups since there are 2 replacement patterns. Group 1 (\+\+) will match double pluses while Group 2 - ([-+]-|-\+) - matches and captures --, +- and -+.
A solution that is Regex only without callback function, so that it can be applicable in other languages that do not have regex replacement callbacks.
var s = '10++10--10+-10-+';
document.body.innerHTML = (s + "||||++=>+,+-=>-,-+=>-,--=>-" // Append replacements
).replace(/(\+\+|--|-\+|\+-)(?=[\s\S]*\1=>([^,]*))|\|\|\|\|[\s\S]*$/g, "$2"
// Perform replacements and remove replacements
)
Related
Am trying to find a regex expression for this result:
string => should be matched (a single word or set of words at the beginning or the ending)
string => should be matched (a single word or set of words in the middle)
{{string}} -- should not be matched (a single word or set of words surrounded by two "{}" should not be matched)
am using this regex in this function :
text = text.replace(RegExp("([^{]{2})[^(\d:)]" + aTags[index].textContent + "\w*
([^}]{2})", 'i'), "{{" + index + ":" + aTags[index].textContent + "}}");
the function should find the textContent of an 'a' tag in a 'text' string and replace it by adding a digit and ':' to the beginning of the textContent so that the result should be something like this :
some text => will became => {{1:some text}}
We can apply the good old *SKIP what's to avoid approach and throw everything that does not need to be replaced in the full match and capture the desired output in group 1:
{{[^}]+}}|(string)
To make this work effectively in JavaScript we have to use a .replace callback function:
const regex = /{{[^}]+}}|(string)/gm;
const str = `string
string
{{string}}`;
var index = 1; //this is your index var and is somehow set from outside
const result = str.replace(regex, function(m, group1) {
if (group1) return `{{${index}:${group1}}}`;
else return m;
});
console.log('Substitution result: ', result);
I had pseudo-coded this a bit since I cannot know where index and aTags[index].textContent is coming from. Adjust as needed.
You cannot use PCRE verbs like (*SKIP)(*F) in a JavaScript regex, i.e. you cannot skip a matched portion of text with the regex means only. In JavaScript, you may match and capture a part of the string you want to later analyze in the replacement callback method (JS String#replace accepts a callback as the replacement argument).
So, in your case the solution will look like
text = text.replace(RegExp("{{.*?}}|(" + aTags[index].textContent + ")", "gi"),
function ($0, $1) {
return $1 ? "{{" + index + ":" + $1 + "}}" : $0;
}
);
I understand the aTags[index].textContent value is alphanumeric, else, consider escaping it for use in a regex pattern.
The pattern will match a {{...}} substring having no } inside (with {{.*?}}) or (|) it will match and capture the text content ((aTags[index].textContent)) into Group 1. When you get a match, you need to pass 2 arguments to the callback, the whole match and Group 1 value. If Group 1 is not empty, you perform string manipulations, else, just insert the match back.
I want to replace a text after a forward slash and before a end parantheses excluding the characters.
My text:
<h3>notThisText/IWantToReplaceThis)<h3>
$('h3').text($('h3').text().replace(regEx, 'textReplaced'));
Wanted result after replace:
notThisText/textReplaced)
I have tried
regex = /([^\/]+$)+/ //replaces the parantheses as well
regex = \/([^\)]+) //replaces the slash as well
but as you can see in my comments neither of these excludes both the slash and the end parantheses. Can someone help?
A pattern like /(?<=\/)[^)]+(?=\))/ won't work in JS as its regex engine does not support a lookbehind construct. So, you should use one of the following solutions:
s.replace(/(\/)[^)]+(\))/, '$1textReplaced$2')
s.replace(/(\/)[^)]+(?=\))/, '$1textReplaced')
s.replace(/(\/)[^)]+/, '$1textReplaced')
s.replace(/\/[^)]+\)/, '/textReplaced)')
The (...) forms a capturing group that can be referenced to with $ + number, a backreference, from the replacement pattern. The first solution is consuming / and ), and puts them into capturing groups. If you need to match consecutive, overlapping matches, use the second solution (s.replace(/(\/)[^)]+(?=\))/, '$1textReplaced')). If the ) is not required at the end, the third solution (replace(/(\/)[^)]+/, '$1textReplaced')) will do. The last solution (s.replace(/\/[^)]+\)/, '/textReplaced)')) will work if the / and ) are static values known beforehand.
You can use str.split('/')
var text = 'notThisText/IWantToReplaceThis';
var splited = text.split('/');
splited[1] = 'yourDesireText';
var output = splited.join('/');
console.log(output);
Try Following: In your case startChar='/', endChar = ')', origString=$('h3').text()
function customReplace(startChar, endChar, origString, replaceWith){
var strArray = origString.split(startChar);
return strArray[0] + startChar + replaceWith + endChar;
}
First of all, you didn't define clearly what is the format of the text which you want to replace and the non-replacement part. For example,
Does notThisText contain any slash /?
Does IWantToReplaceThis contain any parentheses )?
Since there are too many uncertainties, the answer here only shows up the pattern exactly matches your example:
yourText.replace(/(\/).*?(\))/g, '$1textReplaced$2')
var text = "notThisText/IWantToReplaceThis";
text = text.replace(/\/.*/, "/whatever");
output : "notThisText/whatever"`
I'm working with a Google API that returns IDs in the below format, which I've saved as a string. How can I write a Regular Expression in javascript to trim the string to only the characters after the last slash in the URL.
var id = 'http://www.google.com/m8/feeds/contacts/myemail%40gmail.com/base/nabb80191e23b7d9'
Don't write a regex! This is trivial to do with string functions instead:
var final = id.substr(id.lastIndexOf('/') + 1);
It's even easier if you know that the final part will always be 16 characters:
var final = id.substr(-16);
A slightly different regex approach:
var afterSlashChars = id.match(/\/([^\/]+)\/?$/)[1];
Breaking down this regex:
\/ match a slash
( start of a captured group within the match
[^\/] match a non-slash character
+ match one of more of the non-slash characters
) end of the captured group
\/? allow one optional / at the end of the string
$ match to the end of the string
The [1] then retrieves the first captured group within the match
Working snippet:
var id = 'http://www.google.com/m8/feeds/contacts/myemail%40gmail.com/base/nabb80191e23b7d9';
var afterSlashChars = id.match(/\/([^\/]+)\/?$/)[1];
// display result
document.write(afterSlashChars);
Just in case someone else comes across this thread and is looking for a simple JS solution:
id.split('/').pop(-1)
this is easy to understand (?!.*/).+
let me explain:
first, lets match everything that has a slash at the end, ok?
that's the part we don't want
.*/ matches everything until the last slash
then, we make a "Negative lookahead" (?!) to say "I don't want this, discard it"
(?!.*) this is "Negative lookahead"
Now we can happily take whatever is next to what we don't want with this
.+
YOU MAY NEED TO ESCAPE THE / SO IT BECOMES:
(?!.*\/).+
this regexp: [^\/]+$ - works like a champ:
var id = ".../base/nabb80191e23b7d9"
result = id.match(/[^\/]+$/)[0];
// results -> "nabb80191e23b7d9"
This should work:
last = id.match(/\/([^/]*)$/)[1];
//=> nabb80191e23b7d9
Don't know JS, using others examples (and a guess) -
id = id.match(/[^\/]*$/); // [0] optional ?
Why not use replace?
"http://google.com/aaa".replace(/(.*\/)*/,"")
yields "aaa"
How I can get the value after last char(. ; + _ etc.):
e.g.
string.name+org.com
I want to get "com".
Is there any function in jQuery?
Use lastIndexOf and substr to find the character and get the part of the string after it:
var extension = name.substr(name.lastIndexOf(".") + 1);
Demo: http://jsfiddle.net/Guffa/K3BWn/
A simple and readable approch to get the substring after the last occurrence of a character from a defined set is to split the string with a regular expression containing a character class and then use pop() to get the last element of the resulting array:
The pop() method removes the last element from an array and returns that element.
See a JS demo below:
var s = 'string.name+org.com';
var result = s.split(/[.;+_]/).pop();
console.log(result);
to split at all non-overlapping occurrences of the regex by default.
NOTE: If you need to match ^, ], \ or -, you may escape them and use anywhere inside the character class (e.g. /[\^\-\]\\]/). It is possible to avoid escaping ^ (if you do not put it right after the opening [), - (if it is right after the opening [, right before the closing ], after a valid range, or between a shorthand character class and another symbol): /[-^\]\\]/.
Also, if you need to split with a single char, no regex is necessary:
// Get the substring after the last dot
var result = 'string.name+org.com'.split('.').pop();
console.log(result);
Not jQuery, just JavaScript: lastIndexOf and substring would do it (not since the update indicating multiple characters). As would a regular expression with a capture group containing a character class followed by an end-of-string anchor, e.g. /([^.;+_]+)$/ used with RegExp#exec or String#match.
E.g. (live copy | source):
var match = /([^.;+_]+)$/.exec(theStringToTest),
result = match && match[1];
var s = "string.name+org.com",
lw = s.replace(/^.+[\W]/, '');
console.log(lw) /* com */
this will also work for
string.name+org/com
string.name+org.info
You can use RegExp Object.
Try this code:
"http://stackoverflow.com".replace(/.*\./,"");
I'll throw in a crazy (i.e. no RegExp) one:
var s = 'string.name+org.com';
var a = s.split('.'); //puts all sub-Strings delimited by . into an Array
var result = a[a.length-1]; //gets the last element of that Array
alert(result);
EDIT: Since the update of the question is demanding mutiple delimiters to work this is probably not the way to go. Too crazy.....
use javascript function like
url.substr(url.length - 3);
maybe this is too late to consider, this codes works fine for me using jquery
var afterDot = value.substr(value.lastIndexOf('_') + 1);
You could just replate '_' to '.'
var myString = 'asd/f/df/xc/asd/test.jpg'
var parts = myString.split('/');
var answer = parts[parts.length - 1];
console.log(answer);
I'm trying to replace part of a string with the same number of dummy characters in JavaScript, for example: '==Hello==' with '==~~~~~=='.
This question has been answered using Perl and PHP, but I can't get it to work in JavaScript. I've been trying this:
txt=txt.replace(/(==)([^=]+)(==)/g, "$1"+Array("$2".length + 1).join('~')+"$3");
The pattern match works fine, but the replacement does not - the second part adds '~~' instead of the length of the pattern match. Putting the "$2" inside the parentheses doesn't work. What can I do to make it insert the right number of characters?
Use a function for replacement instead:
var txt = "==Hello==";
txt = txt.replace(/(==)([^=]+)(==)/g, function ($0, $1, $2, $3) {
return $1 + (new Array($2.length + 1).join("~")) + $3;
});
alert(txt);
//-> "==~~~~~=="
The issue with the expression
txt.replace(/(==)([^=]+)(==)/g, "$1"+Array("$2".length + 1).join('~')+"$3")
is that "$2".length forces $2 to be taken as a string literal, namely the string "$2", that has length 2.
From the MDN docs:
Because we want to further transform the result of the match before the final substitution is made, we must use a function.
This forces evaluation of the match before the transformation.
With an inline function as parameter (and repeat) -- here $1, $2, $3 are local variables:
txt.replace(/(==)([^=]+)(==)/g, (_,$1,$2,$3) => $1+'~'.repeat($2.length)+$3);
txt = '==Hello==';
//inline function
console.log(
txt.replace(/(==)([^=]+)(==)/g, (_, g1, g2, g3) => g1 + '~'.repeat(g2.length) + g3)
);
The length attribute is being evaluated before the $2 substitution so replace() won't work. The function call suggested by Augustus should work, another approach would be using match() instead of replace().
Using match() without the /g, returns an array of match results which can be joined as you expect.
txt="==Hello==";
mat=txt.match(/(==)([^=]+)(==)/); // mat is now ["==Hello==","==","Hello","=="]
txt=mat[1]+Array(mat[2].length+1).join("~")+mat[3]; // txt is now "==~~~~~=="
You excluded the leading/trailing character from the middle expression, but if you want more flexibility you could use this and handle anything bracketed by the leading/trailing literals.
mat=txt.match(/(^==)(.+)(==$)/)
A working sample uses the following fragment:
var processed = original.replace(/(==)([^=]+)(==)/g, function(all, before, gone, after){
return before+Array(gone.length+1).join('~')+after;
});
The problem in your code was that you always measured the length of "$2" (always a string with two characters). By having the function you can measure the length of the matched part. See the documentation on replace for further examples.