replace number after underscore - javascript

I nee to replace all numbers after underline inside a string.
I think that I can use Regex, but I don't know how to use Regex Syntax
See an example of my string:
milton_0
milton_1

If that is the standard format, You can use split()
var str = 'milton_1';
alert(str.split('_')[1]);

You don't need regex for this. The following code in enough
var str = "milton_0";
str = str.substring(0,str.indexOf("_"));

I'm not sure how specific or broad you want to be, but you can try this:
var starter = "milton_1";
var specialVal = "asdf";
var re = /^(milton_)(\d+)$/;
var replaced = starter.replace(re, function (match, p1) {
return p1 + specialVal;
});
console.log(replaced);
http://jsfiddle.net/ne4cD/
This will match a string starting with "milton_" and ending with digits. It replaces any digits after the "_" with the specialVal value.
An example of simply incrementing that number is:
var starter = "milton_1";
var re = /^(milton_)(\d+)$/;
var replaced = starter.replace(re, function (match, p1, p2) {
return p1 + (+p2 + 1);
});
console.log(replaced);
http://jsfiddle.net/ne4cD/2/
UPDATE:
If the "milton" part isn't static, then you're really only targeting the "_" with digits after it. So something like this:
var starter = "asdfkjlasdfjksadf_1";
var specialVal = "asdf";
var re = /(_)(\d+)/g;
var replaced = starter.replace(re, function (match, p1) {
return p1 + specialVal;
});
console.log(replaced);
http://jsfiddle.net/ne4cD/3/
And maybe a little better to see: http://jsfiddle.net/ne4cD/4/

First of all you need them as list for handling easily.
var listOfStrings = yourStringObject('whateverYourCharacterUnderEachWord').ToList<string>();
After that you need to get rid of number for each string in the list and add what you want.
foreach(string word in listOfStrings){
word = word.Substring(0,word.IndexOf('_')+1);
word = word + "characterThatYouWantToAddHere"
}

Related

JS Split multiple delimiters and get delimiters into input value

I'm asking you today for a little problem :
I have to live control capitalization/no capitalization with js on an input text field like this:
1st character of the entire string must be uppercase
1st character of each word (after space or hyphen) is free (lowercase or uppercase allowed)
All the nother characters must be lowercase
Desired Output: Grand-Father is Nice
I'm not a specialist of JS, i'm using split function, here is my code :
$('#name').on('input change',function() {
var arr1 = $(this).val().split(/[- ]/);
var result1 = "";
for (var x=0; x<arr1.length; x++)
result1+=arr1[x].substring(0,1)+arr1[x].substring(1).toLowerCase()+" ";
var res1 = result1.substring(0, result1.length-1);
var _txt = res1.charAt(0).toUpperCase() + res1.slice(1);
$('#name').val(_txt);
});
The script works but I would like to output the real delimiter found in string, even if it's a space " " or hyphen "-". Actually i can show only space. How can i solve it ?
Actual output: Grand Father is Nice
Any help would be appreciated.
Thank you!
User String.replace() with a RegExp and a callback.
If you know what are your delimiters, you can search for all characters that are no the delimiters, and format them:
var input = 'ègrand-Father is NièCe';
var d = '[^\s\-]'; // not space or dash
var result = input.replace(new RegExp('('+ d +')(' + d + '+)', 'g'), function(m, p1, p2, i) {
var end = p2.toLowerCase();
var start = i === 0 ? p1.toUpperCase() : p1;
return start + end;
});
console.log(result);
If the target browsers support it (Chrome does) or you use a transpiler, such as Babel (plugin), you can use Unicode property escapes in regular expressions (\p):
var input = 'ègrand-Father is NièCe';
var result = input.replace(/(\p{L})(\p{L}+)/gu, function(m, p1, p2, i) {
var end = p2.toLowerCase();
var start = i === 0 ? p1.toUpperCase() : p1;
return start + end;
});
console.log(result);
I'm not entirely sure what your aim is, but let's give it a shot.
This is how you can make all non-first letters be lowercase
let sentence = "this is wRoNg SenTEnce."
sentence.split(" ").map(word => word.charAt(0) + word.slice(1).toLowerCase()).join(" ")
This is how you can make first letter capital:
let sentence = "also Wrong sentence"
sentence.charAt(0).toUpperCase()

Manipulate input string while doing a regex search

trying to find every match in a string and process it with a custom function and replace it in the string. When I set text = to the new string though, it never changes, and in the end remains the unchanged.
function submit () {
var searchTerm = document.querySelector('#search-term').value;
var replaceFunction = Function('input', document.querySelector('#function').value);
var text = '<part id="cursor_crosshair" x="96" y="32" w="16" h="16" focusx="7" focusy="7" />';
var output = text;
var regex = new RegExp('\d', 'g');
var match, matches = [];
//search for replacements
while ((match = regex.exec(text)) != null) {
var beforeMatch = output.substring(0, match.index);
var afterMatch = output.substring(match.index + match[0].length, text.length);
text = beforeMatch + replaceFunction(match[0]) + afterMatch;
console.log(text);
}
console.log('result', text);
}
function replaceFunction (input) {
return input * 2;
}
You can achieve same result with far less code using replace() and its function's callback that takes match as parameter.
var text = '<part id="cursor_crosshair" x="96" y="32" w="16" h="16" focusx="7" focusy="7" />';
text = text.replace(/\d+/g, function(match){
return parseInt(match) * 2;
})
console.log(text)
First of all, you need to use \\ for escape sequence if you are using RegExp constructor. Alternatively you can use the RegExp literal as shown below. Moreover you are using only \d which is going to match a single digit. Instead you should be using \d+ that will match the complete number.
Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
When using the constructor function, the normal string escape rules
(preceding special characters with \ when included in a string) are
necessary. For example, the following are equivalent:
var re = /\w+/;
var re = new RegExp('\\w+');
Then you are trying to manipulate the string using a loop. Instead simply use replace function as shown below.
function submit () {
// var searchTerm = document.querySelector('#search-term').value;
// var replaceFunction = Function('input', document.querySelector('#function').value);
var text = '<part id="cursor_crosshair" x="96" y="32" w="16" h="16" focusx="7" focusy="7" />';
var output = text;
var regex = new RegExp('\\d+', 'g'); // <<<<<< RegExp constructor
// OR
regex = /\d+/g; // <<<<<<< RegExp literal
var match, matches = [];
console.log(text);
output = text.replace(regex, replaceFunction);
console.log('result', output);
}
function replaceFunction (input) {
return parseInt(input) * 2;
}
submit();
Disclaimer: Using RegExp for manipulating HTML elements and attributes is not a good idea and you may end up in unexpected issues if its not used carefully. Use it at your own risk.

using regex to return new filename

Trying to get a filename and have it return a string.
try to turn:
plate-71-winter-hawk-final.jpg
into:
winter hawk final
where plate might also be uppercase. Here is what I have so far, doesn't seem to work
var theRegEx = new RegExp('[Plate|plate]-\d+-(.*).jpg');
var theString = "plate-71-winter-hawk-final.jpg"
var newString = theString.replace(theRegEx, theString);
newString;
Unfortunately, the "Rule #1" doesn't offer a better way:
var newString = theString.replace(/^[Pp]late-\d+-(.*)\.jpg$/, '$1')
.replace(/-/g, ' ');
Take care when you use a string with the object syntax to escape backslahes:
var theRegEx = new RegExp('^[Pp]late-\\d+-(.*)\\.jpg$');
Note that a character class is only a set of characters, you can't use it to put substrings and special regex characters loose their meaning inside it. [Plate|plate] is the same thing than [Pplate|]
You can write it like this too (without string):
var theRegEx = new RegExp(/^[Pp]late-\d+-(.*)\.jpg$/);
Try following script. It's not dependent on length of string as long as it follows standard pattern:
var data = "plate-71-winter-hawk-final.jpg";
var rx = /(?:plate\-\d+\-)(.*)(?=\.)/i;
var match = rx.exec(data);
if(match != null){
data = match[1];
data = data.replace(/\-/g, ' ');
}
console.log(data);
It will print:
winter hawk final

Regex match quotes inside bracket regex

I'm working on a regex that must match only the text inside quotes but not in a comment, my macthes must only the strings in bold
<"love";>
>/*"love"*/<
<>'love'<>
"lo
more love
ve"
I'm stunck on this:
/(?:((\"|\')(.|\n)*?(\"|\')))(?=(?:\/\**\*\/))/gm
The first one (?:((\"|\')(.|\n)*?(\"|\'))) match all the strings
the second one (?=(?:\/\**\*\/)) doesn't match text inside quotes inside /* "mystring" */
bit my logic is cleary wrong
Any suggestion?
Thanks
Maybe you just need to use a negative lookahead to check for the comment end */?
But first, I'd split the string into separate lines
var arrayOfLines = input_str.split(/\r?\n/);
or, without empty lines:
var arrayOfLines = input_str.match(/[^\r\n]+/g);
and then use this regex:
["']([^'"]+)["'](?!.*\*\/)
Sample code:
var rebuilt_string = ''
var re = /["']([^'"]+)["'](?!.*\*\/)/g;
var subst = '<b>$1</b>';
for (i = 0; i < arrayOfLines.length; i++)
{
rebuilt_string = rebuilt_string + arrayOfLines[i].replace(re, subst) + "\r\n";
}
The way to avoid commented parts is to match them before. The global pattern looks like this:
/(capture parts to avoid)|target/
Then use a callback function for the replacement (when the capture group exists, return the match without change, otherwise, replace the match with what you want.
Example:
var result = text.replace(/(\/\*[^*]*(?:\*+(?!\/)[^*]*)*\*\/)|"[^"\\]*(?:\\[\s\S][^"\\]*)*"|'[^'\\]*(?:\\[\s\S][^'\\]*)*'/g,
function (m, g1) {
if (g1) return g1;
return '<b>' + m + '</b>';
});

How can I loop through string and replace all periods except the last one?

Let's say I have a string like this:
var test = my.long.file.name.zip
I am getting the total number of periods in this string with javascript like so:
var dots = (test.match(/\./g) || []).length;
I would then like to replace all of the periods in the string with underscores if there is more than one period in the string.
if(dots>"1"){
var newname = test.replace(/\./g, "_");
console.log(newname);
}
The problem is that this is replacing all of the periods. I would like to keep the last on intact. So what I would like the newname variable to read as would be:
my_long_file_name.zip
My guess is that I should use $.each() somehow to iterate over all except the last one to change the name. How should I do this?
You dont necessarily need a loop, you could do it with a more complex regex, which uses a positive lookahead
The regex /\.(?=.*\.)/g finds periods, but only where there is a subsequent period somewhere further along, which means the last one is not matched.
window.onload = function(){
var input = "my.long.file.name.zip"
var result = input.replace(/\.(?=.*\.)/g,'_')
alert(result);
}
Consider splitting the string on '.', then re-joining all but the last with '_':
var test = "my.long.file.name.zip";
parts = test.split('.');
var plen = parts.length;
if (plen > 1) {
test = parts.slice(0, plen - 1).join('_') +
"." +
parts[plen - 1];
}
console.log(test);
a lookahead group in regex will work:
var test = 'my.long.file.name.zip';
var result = test.replace(/\.(?=[^.]*\.)/g, '_');
alert(result);
this matches a dot followed by ('anything but dot' and another dot), replacing only what is outside the group
var test = 'my.long.file.name.zip';
var last_index = test.lastIndexOf('.');
var newname = test;
if (-1 !== last_index) {
newname = test.replace(/\./g, '_');
newname = newname.substring(0, last_index).concat('.', newname.substring(last_index + 1));
}
console.log(newname);

Categories