How to replace multiple characters except the first? [duplicate] - javascript

This question already has answers here:
How do I replace all occurrences of a string in JavaScript?
(78 answers)
Closed 6 years ago.
I've looked up this question but am new to coding so I'm not quite able to relate other answers to this.
Given a string s, return a string
where all occurrences of its first char have
been changed to '*', except do not change
the first char itself.
e.g. 'babble' yields 'ba**le'
Assume that the string is length 1 or more.
Hint: s.replace(stra, strb) returns a version of string s
where all instances of stra have been replaced by strb.
This is what I have, but this does not replace every character after except the first, it just replaces the next character.
function fixStart(s)
{
var c = s.charAt(0);
return c + s.slice(1).replace(c, '*');
}

function fixStart(s) {
var c = s.charAt(0);
var outputStr = '';
// literate through the entire string pushing letters into a new string unless it is the first letter
for (var i = 0; i < s.length; i++) {
// if the letter is the first letter AND we are not checking the first letter
if (s[i] === c && i !== 0) outputStr += '*'
else outputStr += s[i]
}
return outputStr;
}
console.log(fixStart('hellohahaha'))

To replace all occurrences not just the first, you can use a RegExp:
function fixStart(s) {
var c = s.charAt(0);
return c + s.slice(1).replace(new RegExp(c, 'g'), '*');
}
For example if the value of c is "b", then new RegExp(c, 'g') is equivalent to /b/g.
This will work for simple strings like "babble" in your example. If the string may start with special symbols that mean something in regex, for example '.', then you will need to escape it, as #Oriol pointed out in a comment. See how it's done in this other answer.

Related

Remove "_100" or "_150" or "_num" alone from the end of string [duplicate]

This question already has answers here:
Remove trailing numbers from string js regexp
(2 answers)
Closed 3 years ago.
How would I remove _100 from the end of the string, It should be removed only at the end of the string.
For e.g
marks_old_100 should be "marks_old".
marks_100 should be "marks".
function numInString(strs) {
let newStr = ''
for (let i = 0; i < strs.length; i++) {
let noNumRegex = /\d/
let isAlphRegex = /[a-zA-Z]$/
if (isAlphRegex.test(strs[i])) {
newStr += strs[i]
}
}
return newStr
}
console.log(numInString('marks_100'))
Please check the following snippet:
const s = 'marks_old_100';
// remove any number
console.log(s.replace(/_[0-9]+$/, ''));
// remove three digit number
console.log(s.replace(/_[0-9]{3}$/, ''));
// remove _100, _150, _num
console.log(s.replace(/_(100|150|num)$/, ''));
Try:
string.replace(/_\d+$/g, "")
It makes use of regexes, and the $ matches the end of the string. .replace then replaces it with an empty string, returning the string without \d+ on the end. \d matches any digits, and + means to match more one or more.
Alternatively, if you want to match the end of a word, try:
string.replace(/_\d+\b/g, "")
which utilises \b, to match the end of a word.

Replace nth occurrence of a special character not working RegEx with Google Script [duplicate]

This question already has an answer here:
Javascript regex match fails on actual page, but regex tests work just fine
(1 answer)
Closed 4 years ago.
I am trying to replace the nth occurrence of a character with the following function
It works for strings of letters but I want to replace the 2nd [ in [WORLD!] HELLO, [WORLD!]
I am trying the pattern /.\\[/ which works in RerEx tester but not in my function. I get no error just no replacement
Thanks
function ReplaceNth_n() {
Logger.log(ReplaceNth("[WORLD!] HELLO, [WORLD!]", "/.\\[/", "M", 2))
}
function ReplaceNth(strSearch,search_for, replace_with, Ocur) {
var nth = 0;
strSearch = strSearch.replace(new RegExp(search_for, 'g'), function (match, i, original) {
nth++;
return (nth === Ocur) ? replace_with : match;
});
return strSearch
}
When you create a regular expression with RegExp, you should not include the opening and closing / in the string, and I also don't understand why you added a . there.
Wrong: new RegExp("/test/");
Correct: new RegExp("test");
So the string passed as parameter for search_for should be \\[.
The nth occurrence.
^([^<char>]*(?:<char>[^<char>]*){<N-1>})<char>
Replace with $1<repl_char>
Where the regex string is constructed
regexStr = '^([^' + char + ']*(?:' + char + '[^' + char + ']*){' + (N-1) + '})' + char;
Where char is to be found and N > 0

jQuery multiple replace [duplicate]

This question already has answers here:
How do I replace all occurrences of a string in JavaScript?
(78 answers)
Closed 8 years ago.
I'm trying to remove the euro sign from my string.
Since the string looks like this €33.0000 - €37.5000, I first explode to string on the - after I try to remove the euro sign.
var string = jQuery('#amount').val();
var arr = string.split(' - ');
if(arr[0] == arr[1]){
jQuery(this).find('.last').css("display", "none");
}else{
for(var i=0; i< arr.length; i++){
arr[i].replace('€','');
console.log(arr[i]);
}
}
When I try it on my site, the euro signs aren't removed, when I get the string like this
var string = jQuery('#amount').val().replace("€", "");
Only the first euro sign is removed
.replace() replace only the fisrt occurence with a string, and replace all occurences with a RegExp:
jQuery('#amount').val().replace(/€/g, "")
Try using a regular expression with global replace flag:
"€33.0000 - €37.5000".replace(/€/g,"")
First get rid of the € (Globally), than split the string into Array parts
var noeur = str.replace(/€/g, '');
var parts = noeur.split(" - ");
The problem with your first attempt is that the replace() method returns a new string. It does not alter the one it executes on.
So it should be arr[i] = arr[i].replace('€','');
Also the replace method, by default, replaces the 1st occurrence only.
You can use the regular expression support and pass the global modifier g so that it applies to the whole string
var string = Query('#amount').val().replace(/€/g, "");
var parts = /^€([0-9.]+) - €([0-9.]+)$/.exec(jQuery('#amount').val()), val1, val2;
if (parts) {
val1 = parts[1];
val2 = parts[2];
} else {
// there is an error in your string
}
You can also tolerate spaces here and there: /^\s*€\s*([0-9.]+)\s*-\s*€\s*([0-9.]+)\s*$/

Convert a letter string to a pure letter for use in .match regex [duplicate]

This question already has answers here:
Create RegExps on the fly using string variables
(6 answers)
Closed 8 years ago.
I have an array of alphabets in the form of letter strings
alpha = ['a','b', etc..];
I'm counting up numbers of each letter in a word like so
for (j=0;j<alpha.length;j++){
num = word.match(/alpha[j]/g).length;}
Problem is that, for example, alpha[0] is 'a', not a and match regex only recognizes a .
How can I convert from 'a' to a so that match recognizes it?
To clarify
"ara".match(/a/g) returns ["a","a"] while "ara".match(/'a'/g) returns null.
You can construct a RegExp from a string with the RegExp constructor as described here.
for (j=0;j<alpha.length;j++){
var matches = word.match(new RegExp(alpha[j], "g"));
if (matches) {
num = matches.length;
// other code here to process the match
}
}
This assumes that none of the characters in the alpha array will be special characters in a regular expression because if they are, you will have to escape them so they are treated as normal characters.
As jfriend00 suggests, you can use the RegExp constructor like:
var re, num, matches;
for (j=0; j<alpha.length; j++){
re = new RegExp(alpha[j],'g');
matches = word.match(re);
num = matches? matches.length : 0;
}
Note that another way (shorter, faster, simpler) is:
var num = word.split('a').length - 1; // 'ara' -> 2

Wrap string in brackets but also having random value in string: [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
How can I wrap a string in parantheses that has another random value in it? Look at this for explaining better to understand:
var str = "ss(X)+ss(X)"
INTO:
"(ss(X))+(ss(X))"
NOTE: X can be any value like: "223" or "abc" "2+2+2"
If the string is random data, then this would be impossible, since you don't know what you actually want wrapped. Step 1: find out the condition for "this should be wrapped" versus "this should not be wrapped". We can then do a simple replacement:
var shouldbewrapped = /([a-zA-Z\(\)])+/g;
var wrapped = string.replace(shouldbewrapped, function(found) {
return "(" + found + ")";
});
This does a regexp replace, but instead of replacing a string with a string, it replaces a string with the output of a function run on that string.
(note that the 'g' is crucial, because it makes the replace apply to all matches in your string, instead of stopping after running one replacement)
You can try this:
str = str.replace(/\w*\(\d*\)/g, function () {return '(' + arguments[0] + ')';});
A live demo at jsFiddle
EDIT
Since you've changed the conditions, the task can't be done by Regular Expressions. I've put an example, how you can do this, at jsFiddle. As a side effect, this snippet also detects possible odd brackets.
function addBrackets (string) {
var str = '(' + string,
n, temp = ['('], ops = 0, cls;
str = str.replace(/ /g, '');
arr = str.split('');
for (n = 1; n < arr.length; n++) {
temp.push(arr[n]);
if (arr[n] === '(') {
ops = 1;
while (ops) {
n++;
temp.push(arr[n]);
if (!arr[n]) {
alert('Odd opening bracket found.');
return null;
}
if (arr[n] === '(') {
ops += 1;
}
if (arr[n] === ')') {
ops -= 1;
}
}
temp.push(')');
n += 1;
temp.push(arr[n]);
temp.push('(');
}
}
temp.length = temp.length - 2;
str = temp.join('');
ops = str.split('(');
cls = str.split(')');
if (ops.length === cls.length) {
return str;
} else {
alert('Odd closing bracket found.');
return null;
}
}
Just as a sidenote: If there's a random string within parentheses, like ss(a+b) or cc(c*3-2), it can't be matched by any regular pattern. If you try to use .* special characters to detect some text (with unknown length) within brackets, it fails, since this matches also ), and all the rest of the string too...
I think your going to need to do some string interpolation. Then you can set up some Math.random or whatever you want to generate randomness with.

Categories