JavaScript replace all but last whilst preserving original line breaks - javascript

I have some code which outputs as follows:
function replaceAllButLast(str, splitRegex, pOld, pNew) {
var parts = str.split(splitRegex)
if (parts.length === 1) return str
return parts.slice(0, -1).join(pNew) + pOld + parts.slice(-1)
}
var str = "fred\r\nfred\r\nfred\r\n"
var desiredResult = replaceAllButLast(str, /(?:\r?\n|\r)/, '\n', '\n+')
console.log(desiredResult)
The result is nearly as desired. However, the code assumes that the regex split operation is splitting on \n and thus is replacing it with \n
However, it may actually be splitting on \r\n (windows - as in the example) or \r (old macs)
Does anyone have some code that would give the same output as the code here BUT will preserve the original line break characters whilst still adding the + after a newline (except on the last line).
I am using pure vanilla JavaScript.
PS I must use the regex /(?:\r?\n|\r)/
PPS There is no need to use .split().

This will keep the last newline as it is but others added a +, see replace
var str = "fred\r\nfred\r\nfred\r\n";
var splitRegexp = new RegExp(/(?:\r?\n|\r)/, 'g')
var newstr = str.replace(splitRegexp, function(match, offset, string) {
var follow = string.slice(offset);
var isLast = follow.match(splitRegexp).length == 1;
if (!isLast) {
return match + '+';
} else {
return match;
}
})
console.log(newstr)

I've replaced your regexp with visible chars so you can see what's going on:
var input = "fredEOLfredENDLfredFINfred";
input = input.replace(/(EOL|ENDL|FIN)/g, "$1+");
console.log(input);

Related

Iterating through string and replacing the spaces not working as expected

So I'm trying to return the string with "%20" in between each space, except if there is a space at the beginning or end, where it will be removed instead (eg " Lighthouse Labs " becomes "Lighthouse%20Labs"). For some reason though, my first if statement isn't working, and if there is a space at the beginning or end, it applies the code inside the if statement to ALL the spaces and I have no idea why. I must be fundamentally misunderstanding something here. Any help appreciated!
const urlEncode = function (text) {
for (let i = 0; i < text.length; i++) {
if (text.charAt(0) === " " || text.charAt(text.length - 1) === " ") {
return text.split(" ").join("");
} else {
return text.split(" ").join("%20")
}
}
return text;
};
console.log(urlEncode("Lighthouse Labs")); // Lighthouse%20Labs
console.log(urlEncode(" Lighthouse Labs ")); // LighthouseLabs
console.log(urlEncode("blue is greener than purple for sure")); //blue%20is%20greener%20than%20purple%20for%20sure
console.log(urlEncode(" blue is greener than purple for sure")); //blueisgreenerthanpurpleforsure
console.log(urlEncode("blue is greener than purple for sure "));
//blueisgreenerthanpurpleforsure
You can use trim and replace:
const urlEncode = function (text) {
const regex = / /g
return text.trim().replace(regex, '%20');
}
use this function:
const urlEncode = function (text){
return text.trim().replace(/\s+/g, '%20')
}
Trim() function will remove spaces from beginning and ending of text. The first argument of replace method is a regex that says every whitespace replaced by second argument, the + quantifier means that if there is consecutive whitespaces replace all of them with only one '%20'

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()

Javascript replace utf characters in string

I want to after type Title of post automatically take value and create slug. My code works fine with English Latin characters but problem is when I type characters 'čćšđž'. Code replace first type of this characters in string but if character is repeated than is a problem. So, for testing purpose this title 'šžđčćžđš čćšđžčćšđž čćšđžčć ćčšđžšžčćšđ ćčšžčć' is converted to this slug 'szdcc'.
This is my jquery code:
$('input[name=title]').on('blur', function() {
var slugElement = $('input[name=slug]');
if(slugElement.val()) {
return;
}
slugElement.val(this.value.toLowerCase().replace('ž', 'z').replace('č','c').replace('š', 's').replace('ć', 'c').replace('đ', 'd').replace(/[^a-z0-9-]+/g, '-').replace(/^-+|-+$/g, ''));
});
How to solve this problems? Also is it possible to this few characters put in same replace() function?
Try this:
function clearText(inp) {
var wrong = 'čćšđž';
var right = 'ccsdz';
var re = new RegExp('[' + wrong + ']', 'ig');
return inp.replace(re, function (m) { return right.charAt(wrong.indexOf(m)); });
}
replace() only replaces the first occurrence unless regex is used with global modifier. You will need to change them all to regular expression.
replace(/ž/g, "z")
As far as I know, it will not be possible to use a single replace() in your case.
If you are concerned with chaining a bunch of .replace() together, you might be better off writing some custom code to replace these characters.
var newStr = "";
for (var i = 0; i < str.length; i++) {
var c = str.charAt(i);
switch (c) {
case "ž": newStr += "z"; break;
default: newStr += c; break;
}
}

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>';
});

Javascript regex - split string

Struggling with a regex requirement. I need to split a string into an array wherever it finds a forward slash. But not if the forward slash is preceded by an escape.
Eg, if I have this string:
hello/world
I would like it to be split into an array like so:
arrayName[0] = hello
arrayName[1] = world
And if I have this string:
hello/wo\/rld
I would like it to be split into an array like so:
arrayName[0] = hello
arrayName[1] = wo/rld
Any ideas?
I wouldn't use split() for this job. It's much easier to match the path components themselves, rather than the delimiters. For example:
var subject = 'hello/wo\\/rld';
var regex = /(?:[^\/\\]+|\\.)+/g;
var matched = null;
while (matched = regex.exec(subject)) {
print(matched[0]);
}
output:
hello
wo\/rld
test it at ideone.com
The following is a little long-winded but will work, and avoids the problem with IE's broken split implementation by not using a regular expression.
function splitPath(str) {
var rawParts = str.split("/"), parts = [];
for (var i = 0, len = rawParts.length, part; i < len; ++i) {
part = "";
while (rawParts[i].slice(-1) == "\\") {
part += rawParts[i++].slice(0, -1) + "/";
}
parts.push(part + rawParts[i]);
}
return parts;
}
var str = "hello/world\\/foo/bar";
alert( splitPath(str).join(",") );
Here's a way adapted from the techniques in this blog post:
var str = "Testing/one\\/two\\/three";
var result = str.replace(/(\\)?\//g, function($0, $1){
return $1 ? '/' : '[****]';
}).split('[****]');
Live example
Given:
Testing/one\/two\/three
The result is:
[0]: Testing
[1]: one/two/three
That first uses the simple "fake" lookbehind to replace / with [****] and to replace \/ with /, then splits on the [****] value. (Obviously, replace [****] with anything that won't be in the string.)
/*
If you are getting your string from an ajax response or a data base query,
that is, the string has not been interpreted by javascript,
you can match character sequences that either have no slash or have escaped slashes.
If you are defining the string in a script, escape the escapes and strip them after the match.
*/
var s='hello/wor\\/ld';
s=s.match(/(([^\/]*(\\\/)+)([^\/]*)+|([^\/]+))/g) || [s];
alert(s.join('\n'))
s.join('\n').replace(/\\/g,'')
/* returned value: (String)
hello
wor/ld
*/
Here's an example at rubular.com
For short code, you can use reverse to simulate negative lookbehind
function reverse(s){
return s.split('').reverse().join('');
}
var parts = reverse(myString).split(/[/](?!\\(?:\\\\)*(?:[^\\]|$))/g).reverse();
for (var i = parts.length; --i >= 0;) { parts[i] = reverse(parts[i]); }
but to be efficient, it's probably better to split on /[/]/ and then walk the array and rejoin elements that have an escape at the end.
Something like this may take care of it for you.
var str = "/hello/wo\\/rld/";
var split = str.replace(/^\/|\\?\/|\/$/g, function(match) {
if (match.indexOf('\\') == -1) {
return '\x00';
}
return match;
}).split('\x00');
alert(split);

Categories