JavaScript regex: find non-numeric character - javascript

Let's say I have these two strings: "5/15/1983" and "1983.05.15". Assume that all characters in the string will be numeric, except a "separator" character that can appear anywhere in the string. There will be only one separator character; all instances of any given non-numeric character in the string will be identical.
How can I use regex to extract this character? Is there a more efficient way than the one below?
"05-15-1983".replace(/\d/g, "")[0];
Thanks!

"05-15-1983".match(/\D/)
Technically, this returns an array containing one string, but it will implicitly convert to the string most places you need this.

Though i could not exactly get what you trying to do i tried to extract the numbers only in one string and the seperator in next string.
I used the above:
<script>
var myStr1 = "1981-01-05";
var myStr2 = "1981-01-05";
var RegEx1 = /[0-9]/g;
var RegEx2 = /[^0-9]/g;
var RegEx3 = /[^0-9]/;
document.write( 'First : ' + myStr1.match( RegEx1 ) + '<br />' );
document.write( 'tooo : ' + myStr2.replace( RegEx2, "" ) + '<br />' );
document.write( 'Second : ' + myStr1.match( RegEx2 ) + '<br />' );
document.write( 'Third : ' + myStr1.match( RegEx3 ) + '<br />' );
</script>
Output:
First : 1,9,8,1,0,1,0,5
tooo : 19810105
Second : -,-
Third : -
I hope you get your answer

Clearly tired or not paying attention on my previous answer. Sorry about that. What I should have written was:
var regexp = new RegExp("([^0-9])","g");
var separator = regexp.exec("1985-10-20")[1];
Of course, Matthew Flaschen's works just as well. I just wanted to correct mine.

Related

Is there a limit to regex for javascript pattern searches?

This is as simplified as I can get my problem to reproduce. I get the same result in Safari and Chrome...
var temp = 'a b s40 x';
var div = $('#test');
div.append('<br>' + temp)
var problem = temp.replace(/(^| )(a|c|s\d{1,3}|x)( |$)/g, ' ').trim();
div.append('<br>' + problem); //=b x
var solution = temp.replace(/(^| )(a|c|s\d{1,3})( |$)/g, ' ').replace(/(^| )x( |$)/g, ' ').trim();
div.append('<br>' + solution); //=b
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='test'>Hello...
</div>
problem uses: (a|c|s\d{1,3}|x)
solution uses: (a|c|s\d{1,3}) and a second replace to get the x...
why is solution != problem??
My fiddle: https://jsfiddle.net/zo5caun2/
The problem is that it won't replace overlapping matches. When it matches s40, the match includes the spaces before and after the word. It can't match x because there's no space before it, since that was part of the previous match. And it's not at the beginning, so ^ doesn't match before it, either.
That doesn't happen in solution because you're doing two separate replacements, so the second replace doesn't care what was matched in the first one.
Use \b to match word boundaries instead of explicit spaces.
var temp = 'a b s40 x';
var div = $('#test');
div.append('<br>' + temp)
var problem = temp.replace(/\b(a|c|s\d{1,3}|x)\b/g, ' ').trim();
div.append('<br>' + problem); //=b x
var solution = temp.replace(/\b(a|c|s\d{1,3})\b/g, ' ').replace(/\bx\b/g, ' ').trim();
div.append('<br>' + solution); //=b
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='test'>Hello...
</div>
If you just need modify first regex to have the same result as in the second regex this should solve your problem.
i'm not sure why you put this (^| ) - start or space and space or end( |$). you can use \b
If you need ensure that are some chars in front or after capture then you can use look behind.
var temp = 'a b s40 x';
var problem = temp.replace(/\b(a|c|s\d{1,3}|x)\b/g,' ').trim();
console.log(problem)
var solution = temp.replace(/(^| )(a|c|s\d{1,3})( |$)/g,' ').replace(/(^| )x( |$)/g,' ').trim();
console.log(solution)

jQuery Replace Second Space of Sentence

I want to replace second space occurrence of the sentence with a br.
I have tried this but it is deleting the rest.
var title = "My Title Needs Brace".split(" ").slice(0, 2).join(" ");
That will do the trick:
"My Title Needs Brace"
.split(' ')
.reduce(function (str, part, i) {
return str + (i === 2 ? '<br/>' : ' ') + part
});
// "My Title<br/>Needs Brace"
Let's break it and see how it works:
First, we take the string and split it. we'll use " " as our separator
"My Title Needs Brace".split(' ')
// ["My", "Title", "Needs", "Brace"]
Second, we'll use reduce to combine the array back into one string
["My", "Title", "Needs", "Brace"]
.reduce(function (str, part) { return str + ' ' + part }, '');
// "My Title Needs Brace"
Why reduce and not join?
The advantage of reduce over join is that it allows us to use a function, which will give us a fine-grained control over how we join back each part of the string
Now, all that left is to replace the 2nd space with <br/>,
for that, we'll use the 3rd argument of the reduce function, which stands for the index, and ask:
is this the 3rd part? use <br/>
otherwise, use " "
"My Title Needs Brace"
.split(' ')
.reduce(function (str, part, i) {
return str + (i === 2 ? '<br/>' : ' ') + part
});
// "My Title<br/>Needs Brace"
Note that this is the index of the string "part", not the spaces between them so the index is 2, not 1.
More about:
split
reduce
join
Try the following:
var title = "My Title Needs Brace".split(" ");
title.forEach(function(item, i, title){
if(i==1)
title[i] += "<br/>";
else
title[i] += ' ';
})
console.log(title.join(''));
I want to replace second space occurrence of the sentence with a br.
The simple way to do that is to add "<br/>" to the second element.
Here is the Code.
$(document).ready(function(){
var title = "My Title Needs Brace".split(" ");
title[1] = title[1]+"<br/>";
var newstr = title.join(" ");
$("#textd").html(newstr);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="textd">
</div>
maybe that will help :
var title = "My Title Needs Brace".split(" ");
t1=title [0]; My
t2=title[1]; // Title
t3=title[2]; // Needs
t4=title[3]; // Brace
you can drew here anything :
var htmlString = '' + t1 +''+ t2 + '<br />' + t3 +''+ t4 + '';
$('Anywhere').append(htmlString);
You can do this without splitting the string:
var title = 'My Title Needs Brace'.replace(/( .*?) /, '$1<br>');
Here, String.replace takes a RegExp and a string as arguments. The regex matches everything from the first space up through the second space, keeping everything except the second space in a capturing group. The string replaces the entire match with the contents of the capturing group, followed by '<br>'. Since the capturing group doesn't include the second space, this effectively only replaces the second space.

How can I change the text in just a part of my string with javascript?

I have a javascript string that contains the following:
data-href="/Admin/Edit?pk=0001I&rk=50050055"
How can I change this string so the value of rk is changed to a value held in the string newRowKey? Not sure if it helps but the data format always looks like this with the rk followed by an = and then terminated with the "
datahref="/Admin/Edit?pk=0001I&rk=50050055";
to change it if your building the URL
datahref="/Admin/Edit?pk=0001I&rk="+ newRowKey;
or replace it if you know the existing value
datahref.replace("50050055", newRowKey);
if you do not know the value of rk, but you know its last in the URL, you could use indexOf to find it.
datahref = datahref.substring(0,datahref.indexOf("rk=")+3) + newRowKey;
Maybe you want a regular expression to replace that rk.
newRowKey = 'XXXXXX'
s = 'Edit?pk=0001I&rk=50050055';
s2 = s.replace(/(.*;)(rk=)(.*)(&|)/, '$1$2' + newRowKey)
alert( s + "\n" + s2 );
//2nd test
s = 'Edit?pk=0001I&rk=50050055&';
s2 = s.replace(/(.*;)(rk=)(.*)(&|)/, '$1$2' + newRowKey)
alert( s + "\n" + s2 );
​demo: http://jsfiddle.net/fedmich/g3TjE/
data_href.replace(/rk=.*$/,'rk=' + newRowKey);

Regular expression for replacing string with javascript

I need help in writing regular expression:
part of my string is fixed and another part of its variable.
only if fixed AND variable string exist i need to alter the string other wise no.
Fixed string:example: AA.BBB.COM
Variable string (may or mayn't exist ): US, but if exist it will be always two letter string with any combination of letter.
In below string if I have variable two letter string exist I want to append “.new”
1 ) https://XY**.US**.AA.BBB.COM
Output: https:// XYZ12**.US.NEW**.AA.BBB.COM
2 ) https://XY.UK.AA.BBB.COM
Output: https:// XYZ12.UK.NEW.AA.BBB.COM
3) https://XY.AA.BBB.COM (no variable string so no change)
Output: https:// XY.AA.BBB.COM
Thanks for your help .
Raghav
Something like the following should get you started, there are other methods. Splitting and parsing might suit better depending on your real requirements:
var s = 'https://XY.US.AA.BBB.COM';
var t = 'https://XY.UK.AA.BBB.COM';
var u = 'https://XY.AA.BBB.COM';
var re = /(\.)(UK|US)(\.)/;
alert(
s.replace(re, '$1' + '$2' + '.NEW' + '$3') + '\n' +
t.replace(re, '$1' + '$2' + '.NEW' + '$3') + '\n' +
u.replace(re, '$1' + '$2' + '.NEW' + '$3')
);

javascript regex to replace a substring

In javascript, how would I use a regular expression to replace everything to the right of "Source="
Assume, for example:
var inStr="http://acme.com/mainpage.aspx?ID=25&Source=http://acme.com/fruitPage.aspx"
var newSoruceValue="http://acme.com/vegiePage.aspx"
Goal is to get this value in outStr:
var outStr="http://acme.com/mainpage.aspx?ID=25&Source=http://acme.com/vegiePage.aspx"
Thanks!!
Assumes that source= will always be at the end
var inStr="http://acme.com/mainpage.aspx?ID=25&Source=http://acme.com/fruitPage.aspx"
var newSourceValue="http://acme.com/vegiePage.aspx"
var outStr = inStr.replace( /(Source=).*/, "$1" + newSourceValue);
Is "Source" always linked to the first occurrance of "&"?
You could use
indexOf("&") + 7
(number of letters in the word "Source" + one for "=").
Then create the new string by appending the new source to the substring using the index from before.
string.replace( /pattern/, replace_text );
var outStr = inStr.replace( /&Source=.*$/, "&Source=" + newSoruceValue );
or
var outStr = inStr.replace( /(&Source=).*$/, "$1" + newSoruceValue )

Categories

Resources