我正在尝试创建一个过滤器来替换文章中的字符。
我想在字符串中找到所有匹配的元素,并用数组中的元素替换它们,但这是行不通的。如何解决?
//string to replace -> ”Lorem ipsum dolor sit amet – consectetur adipiscing elit. Suspendisse vitae augue ornare, ultricies ligula at, tempor felis – aenean ac placerat turpis. Nullam finibus lacus sit amet tortor consequat, venenatis malesuada eros volutpat. Proin varius nibh sit amet urna lobortis placerat. Donec rhoncus nibh vitae ultricies rutrum. Curabitur porta nisi eu rhoncus pulvinar. Nulla sit amet sollicitudin odio. Aliquam mi odio, malesuada ac arcu vitae, bibendum convallis risus.„
function charReplace(value) {
let desc = value;
const toReplace = {
'–': '–',
'”': '"',
'„': '"'
};
for (let key in toReplace) {
desc.replace(key, toReplace[key]);
}
return desc;
}
答案 0 :(得分:1)
我认为这是最短的。 无需循环,您可以只使用managesdk command
您可以将函数指定为第二个参数。在这种情况下, 匹配完成后将调用该函数。
像这样:
var str = "”Lorem ipsum dolor sit amet – consectetur adipiscing elit. Suspendisse vitae augue ornare, ultricies ligula at, tempor felis – aenean ac placerat turpis. Nullam finibus lacus sit amet tortor consequat, venenatis malesuada eros volutpat. Proin varius nibh sit amet urna lobortis placerat. Donec rhoncus nibh vitae ultricies rutrum. Curabitur porta nisi eu rhoncus pulvinar. Nulla sit amet sollicitudin odio. Aliquam mi odio, malesuada ac arcu vitae, bibendum convallis risus.„";
str = str.replace(/(–)|(”)|(„)/g,(str, p1, p2, p3)=>{
if(p1) return "–";
if(p2 || p3 ) return '"';
});
console.log(str);
请记住该表达式,我们正在寻找–
,”
和„
的精确匹配项,因此,如果您拥有„
表达式,则找不到匹配项。
答案 1 :(得分:1)
您可以将正则表达式与所有带有管道的连接键一起使用(正则表达式对替代符号进行签名),并为替换项提供一个功能,该功能将找到的键作为替换对象的键。
function charReplace(value) {
const toReplace = { '–': '–', '”': '"', '„': '"' };
return value.replace(
new RegExp(Object.keys(toReplace).join('|'), 'g'),
k => toReplace[k]
);
}
var string = "”Lorem ipsum dolor sit amet – consectetur adipiscing elit. Suspendisse vitae augue ornare, ultricies ligula at, tempor felis – aenean ac placerat turpis. Nullam finibus lacus sit amet tortor consequat, venenatis malesuada eros volutpat. Proin varius nibh sit amet urna lobortis placerat. Donec rhoncus nibh vitae ultricies rutrum. Curabitur porta nisi eu rhoncus pulvinar. Nulla sit amet sollicitudin odio. Aliquam mi odio, malesuada ac arcu vitae, bibendum convallis risus.„";
console.log(charReplace(string));
答案 2 :(得分:1)
如果您尝试使用字符串替换,它将仅替换该字符串的第一个实例。如果使用regex,它将替换该字符串的所有匹配项。这应该相当简单,并且正则表达式非常易读。我会做这样的事情:
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import java.util.Calendar;
/**
* Created by moonis
* on 23/06/18.
*/
public class CustomClock extends View {
private int height, width = 0;
private int padding = 0;
private int fontSize = 0;
int numeralSpacing = 0;
private int handTruncation, hourHandTruncation = 0;
private int radius = 0;
private Paint paint;
private boolean isInit;
private int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
private Rect rect = new Rect();
public CustomClock(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
setFocusable(true);
setFocusableInTouchMode(true);
}
private void initClock() {
height = getHeight();
width = getWidth();
padding = numeralSpacing + 50;
fontSize = (int) DeviceDimensionHelper.convertDpToPixel(13, getContext());
int min = Math.min(height, width);
radius = min / 2 - padding;
handTruncation = min / 20;
hourHandTruncation = min / 7;
paint = new Paint();
isInit = false;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (!isInit) {
initClock();
}
canvas.drawColor(Color.BLACK);
drawCircle(canvas);
drawCentre(canvas);
drawNumeral(canvas);
drawHands(canvas);
postInvalidateDelayed(500);
}
private void drawCircle(Canvas canvas) {
paint.reset();
paint.setColor(Color.WHITE);
paint.setAntiAlias(true);
paint.setStrokeWidth(5);
paint.setStyle(Paint.Style.STROKE);
canvas.drawCircle(width / 2, height / 2, radius + padding - 10, paint);
}
private void drawCentre(Canvas canvas) {
paint.setStyle(Paint.Style.FILL);
canvas.drawCircle(width / 2, height / 2, 12, paint);
}
private void drawNumeral(Canvas canvas) {
paint.setTextSize(fontSize);
for (int number : numbers) {
String tmp = String.valueOf(number);
paint.getTextBounds(tmp, 0, tmp.length(), rect);
double angle = Math.PI / 6 * (number - 3);
int x = (int) (width / 2 + Math.cos(angle) * radius - rect.width() / 2);
int y = (int) (height / 2 + Math.sin(angle) * radius - rect.height() / 2);
canvas.drawText(tmp, x, y, paint);
}
}
private void drawHands(Canvas canvas) {
Calendar c = Calendar.getInstance();
float hour = c.get(Calendar.HOUR_OF_DAY);
hour = hour > 12 ? hour - 12 : hour;
drawHand(canvas, (hour + c.get(Calendar.MINUTE) / 60) * 5f, true);
drawHand(canvas, c.get(Calendar.MINUTE), false);
drawHand(canvas, c.get(Calendar.SECOND), false);
}
private void drawHand(Canvas canvas, double loc, boolean isHour) {
double angle = Math.PI * loc / 30 - Math.PI / 2;
int handRadius = isHour ? radius - handTruncation - hourHandTruncation : radius - handTruncation;
canvas.drawLine(width / 2, height / 2, (float) (width / 2 + Math.cos(angle) * handRadius), (float) (height / 2 + Math.sin(angle) * handRadius), paint);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float touchX = event.getX();
float touchY = event.getY();
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
//code to move clock hands on screen gestures
break;
case MotionEvent.ACTION_MOVE:
//code to move clock hands on screen gestures
break;
default:
return false;
}
//redraw view
postInvalidate();
return true;
}
}
我还没有测试上面的代码,但是它的本质应该可以在您的函数中正常工作。如果要扩展它,只需扩展替换数组即可。
答案 3 :(得分:1)
JS替换函数的返回值,您应该分配值,然后使用它
let desc = value;
const toReplace = {
'–': '–',
'”': '"',
'„': '"'
};
for (let key in toReplace) {
desc = desc.replace(key, toReplace[key]);
}
return desc;
希望它能对您有所帮助。
答案 4 :(得分:0)
使用.split(...).join(...)
:
// string to replace
const string = '”Lorem ipsum dolor sit amet – consectetur adipiscing elit. Suspendisse vitae augue ornare, ultricies ligula at, tempor felis – aenean ac placerat turpis. Nullam finibus lacus sit amet tortor consequat, venenatis malesuada eros volutpat. Proin varius nibh sit amet urna lobortis placerat. Donec rhoncus nibh vitae ultricies rutrum. Curabitur porta nisi eu rhoncus pulvinar. Nulla sit amet sollicitudin odio. Aliquam mi odio, malesuada ac arcu vitae, bibendum convallis risus.„';
function charReplace(value) {
const toReplace = {
'–': '–',
'”': '"',
'„': '"'
};
let desc = value;
for (const key of Object.keys(toReplace)) {
desc = desc.split(key).join(toReplace[key]);
}
return desc;
}
console.log(charReplace(string));
迭代替换项并使用.replace(new RegExp(...))
替换它们:
// string to replace
const string = '”Lorem ipsum dolor sit amet – consectetur adipiscing elit. Suspendisse vitae augue ornare, ultricies ligula at, tempor felis – aenean ac placerat turpis. Nullam finibus lacus sit amet tortor consequat, venenatis malesuada eros volutpat. Proin varius nibh sit amet urna lobortis placerat. Donec rhoncus nibh vitae ultricies rutrum. Curabitur porta nisi eu rhoncus pulvinar. Nulla sit amet sollicitudin odio. Aliquam mi odio, malesuada ac arcu vitae, bibendum convallis risus.„';
function charReplace(value) {
const toReplace = {
'–': '–',
'”': '"',
'„': '"'
};
let desc = value;
for (const entity of Object.keys(toReplace)) {
desc = desc.replace(new RegExp(entity, 'g'), toReplace[entity]);
}
return desc;
}
console.log(charReplace(string));
加入替换项并使用替换器功能:
.replace(new RegExp(Object.keys(replacements).join('|'), 'g'), match => replacements[match])
// string to replace
const string = '”Lorem ipsum dolor sit amet – consectetur adipiscing elit. Suspendisse vitae augue ornare, ultricies ligula at, tempor felis – aenean ac placerat turpis. Nullam finibus lacus sit amet tortor consequat, venenatis malesuada eros volutpat. Proin varius nibh sit amet urna lobortis placerat. Donec rhoncus nibh vitae ultricies rutrum. Curabitur porta nisi eu rhoncus pulvinar. Nulla sit amet sollicitudin odio. Aliquam mi odio, malesuada ac arcu vitae, bibendum convallis risus.„';
function replace(string, replacements) {
return string.replace(new RegExp(Object.keys(replacements).join('|'), 'g'), match => replacements[match]);
}
console.log(replace(string, {
'–': '–',
'”': '"',
'„': '"'
}));