How to get next 3 characters after a substring if it exist inside a string? - javascript

I have this string that's. The &# substring is common but number after it changes in almost every object of my JSON data. So I want to detect if there is this substring, then get next three characters after it replace it with something else. How can I do it?

You can do it like this
var para = 'that's';
para = para.substr(para.indexOf('#')+1, 3);
syntax:
substr(start, length)
indexOf(searchvalue, [start])

Assuming you want to replace everything from &# until ; (if not, please update your question by specifying expected output):
You can use String.prototype.replace() with a regular expression:
var para = 'some string ' middle † end';
para = para.replace(/&#([\d]*);/g, 'replacement');
The g modifier is important to replace all occurences in the string.
With the RegEx used, you can include the found number (between &# and ;) in the replacement string by using $1.

you can define and use a utility function to replace HTML entities like that:
function decode(text, replaceWith = '') {
return text.replace(/&#(\d+);/g, replaceWith)
}

Related

Using regex to split double hyphen but not single hyphen

I have an html element id that looks like this:
dp__1-2--1-3
I'm trying to use the JavaScript split() function to lop off and return the final '1-3'
My regex skills are poor but a bit of searching around got me to this point:
var myId = "dp__1-2--1-3";
var myIdPostFix = myId.split(/[\-\-]+/).pop();
Unfortunately that returns me only the '3'.
So my question is how do I split double hyphens but NOT single hyphens?
It's the brackets in the regular expression that keeps it from working. A set will match one of any of the characers in it, so [\-\-] is the same as [\-], i.e. matching a single hyphen.
Just remove the brackets:
var myIdPostFix = myId.split(/--/).pop();
or just use the string '--' instead of a regular expression:
var myIdPostFix = myId.split('--').pop();
split accepts a regular expression or a string as the first argument.
You were very close. You can achieve what you want with:
var myIdPostFix = myId.split("--").pop();

RegExp match a single quoted text without quotes - JavaScript

I'm sorry if it is a confusing question. I was trying to find a way to do this but couldn't find it so, if it is a repeated question, my apologies!
I have a text something like this: something:"askjnqwe234"
I want to be able to get askjnqwe234 using a RegExp. You can notice I want to omit the quotes. I was trying this using /[^"]+(?=(" ")|"$)/g but it returns an array. I want a RegExt to return a single string, not an array.
I don't know if it's possible but I do not want to specify the position of the array; something like this:
var x = string.match(/[^"]+(?=(" ")|"$)/g)[0];
Thanks!
Try:
/"([^"]*)"/g
in English: look for " the match and record anything that isn't " till you see another "".
match and exec always return an array or null, so, assuming you have a single double-quoted value and no newlines in the string, you could use
var x;
var str = 'something:"askjnqwe234"';
x = str.replace( /^[^"]*"|".*/g, '' );
// "askjnqwe234"
Or, if you may have other quoted values in the string
x = str.replace( /.*?something:"([^"]*)".*/, '$1' );
where $1 refers to the substring captured by the sub-pattern [^"]* between the ().
Further explanation on request.
Notwithstanding the above, I recommend that you tolerate the array indexing and just use match.
You can capture the information inside quotes like this, assuming it matches:
var x = string.match(/something:"([^"]*)"/)[1];
The memory capture at index 1 is the part inside the double quotes.
If you're not sure it will match:
var match = string.match(/something:"([^"]*)"/);
if (match) {
// use match[1] here
}

java script Regular Expressions patterns problem

My problem start with like-
var str='0|31|2|03|.....|4|2007'
str=str.replace(/[^|]\d*[^|]/,'5');
so the output becomes like:"0|5|2|03|....|4|2007" so it replaces 31->5
But this doesn't work for replacing other segments when i change code like this:
str=str.replace(/[^|]{2}\d*[^|]/,'6');
doesn't change 2->6.
What actually i am missing here.Any help?
I think a regular expression is a bad solution for that problem. I'd rather do something like this:
var str = '0|31|2|03|4|2007';
var segments = str.split("|");
segments[1] = "35";
segments[2] = "123";
Can't think of a good way to solve this with a regexp.
Here is a specific regex solution which replaces the number following the first | pipe symbol with the number 5:
var re = /^((?:\d+\|){1})\d+/;
return text.replace(re, '$15');
If you want to replace the digits following the third |, simply change the {1} portion of the regex to {3}
Here is a generalized function that will replace any given number slot (zero-based index), with a specified new number:
function replaceNthNumber(text, n, newnum) {
var re = new RegExp("^((?:\\d+\\|){"+ n +'})\\d+');
return text.replace(re, '$1'+ newnum);
}
Firstly, you don't have to escape | in the character set, because it doesn't have any special meaning in character sets.
Secondly, you don't put quantifiers in character sets.
And finally, to create a global matching expression, you have to use the g flag.
[^\|] means anything but a '|', so in your case it only matches a digit. So it will only match anything with 2 or more digits.
Second you should put the {2} outside of the []-brackets
I'm not sure what you want to achieve here.

assign matched values from jquery regex match to string variable

I am doing it wrong. I know.
I want to assign the matched text that is the result of a regex to a string var.
basically the regex is supposed to pull out anything in between two colons
so blah:xx:blahdeeblah
would result in xx
var matchedString= $(current).match('[^.:]+):(.*?):([^.:]+');
alert(matchedString);
I am looking to get this to put the xx in my matchedString variable.
I checked the jquery docs and they say that match should return an array. (string char array?)
When I run this nothing happens, No errors in the console but I tested the regex and it works outside of js. I am starting to think I am just doing the regex wrong or I am completely not getting how the match function works altogether
I checked the jquery docs and they say that match should return an array.
No such method exists for jQuery. match is a standard javascript method of a string. So using your example, this might be
var str = "blah:xx:blahdeeblah";
var matchedString = str.match(/([^.:]+):(.*?):([^.:]+)/);
alert(matchedString[2]);
// -> "xx"
However, you really don't need a regular expression for this. You can use another string method, split() to divide the string into an array of strings using a separator:
var str = "blah:xx:blahdeeblah";
var matchedString = str.split(":"); // split on the : character
alert(matchedString[1]);
// -> "xx"
String.match
String.split

How to replace multiple strings with replace() in Javascript

I'm guessing this is a simple problem, but I'm just learning...
I have this:
var location = (jQuery.url.attr("host"))+(jQuery.url.attr("path"));
locationClean = location.replace('/',' ');
locationArray = locationClean.split(" ");
console.log(location);
console.log(locationClean);
console.log(locationArray);
And here is what I am getting in Firebug:
stormink.net/discussed/the-ideas-behind-my-redesign
stormink.net discussed/the-ideas-behind-my-redesign
["stormink.net", "discussed/the-ideas-behind-my-redesign"]
So for some reason, the replace is only happening once? Do I need to use Regex instead with "/g" to make it repeat? And if so, how would I specifiy a '/' in Regex? (I understand very little of how to use Regex).
Thanks all.
Use a pattern instead of a string, which you can use with the "global" modifier
locationClean = location.replace(/\//g,' ');
The replace method only replaces the first occurance when you use a string as the first parameter. You have to use a regular expression to replace all occurances:
locationClean = location.replace(/\//g,' ');
(As the slash characters are used to delimit the regular expression literal, you need to escape the slash inside the excpression with a backslash.)
Still, why are you not just splitting on the '/' character instead?
You could directly split using the / character as the separator:
var loc = location.host + location.pathname, // loc variable used for tesing
locationArray = loc.split("/");
This can be fixed from your javascript.
SYNTAX
stringObject.replace(findstring,newstring)
findstring: Required. Specifies a string value to find. To perform a global search add a 'g' flag to this parameter and to perform a case-insensitive search add an 'i' flag.
newstring: Required. Specifies the string to replace the found value from findstring
Here's what ur code shud look like:
locationClean = location.replace(new RegExp('/','g'),' ');
locationArray = locationClean.split(" ");
njoi'

Categories

Resources